我在玩std::variant, lambdas
和std::future
,当我试图将它们组合在一起时,得到了超级奇怪的结果。下面举例说明:无法初始化各种lambda表达式的std :: variant
using variant_t = std::variant<
std::function<std::future<void>(int)>,
std::function<void(int)>
>;
auto f1 = [](int) { return std::async([] { return 1; }); };
auto f2 = [](int) { return std::async([] { }); };
variant_t v1(std::move(f1)); // !!! why DOES this one compile when it SHOULDN'T?
auto idx1 = v1.index(); //equals 1. WHY?
variant_t v2(std::move(f2)); // !!! why DOESN'T this one compile when it SHOULD?
以下是编译错误:
Error C2665 'std::variant<std::function<std::future<void> (int)>,std::function<void (int)>>::variant': none of the 2 overloads could convert all the argument types
OK,从返回void
到int
让改变variant
的物品签名:
using variant_t = std::variant<
std::function<std::future<int>(int)>,
std::function<int(int)>
>;
variant_t v1(std::move(f1)); // COMPILES (like it should)
auto idx1 = v1.index(); // equals 0
variant_t v2(std::move(f2)); // DOESN'T compile (like it should)
这是什么鬼去这里?为什么std::future<void>
如此特别?
注意:'std :: variant'是一个C++ 17特性,而不是C++ 11。 – Rakete1111
你的编译错误来自第二个例子,但你的问题看起来像是从你的第一个例子。 – Barry