Tôi đang chơi với std::variant, lambdas
và std::future
và có kết quả siêu lạ khi tôi cố gắng kết hợp chúng lại với nhau. Dưới đây là ví dụ:Không thể khởi tạo std :: biến thể với các biểu thức lambda khác nhau
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?
Đây là lỗi biên dịch:
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, cho phép thay đổi variant
's mục chữ ký từ trở void
để int
:
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)
Cái quái gì thế đang diễn ra ở đây? Tại sao là std::future<void>
rất đặc biệt?
Lưu ý: 'std :: variant' là tính năng C++ 17, không phải C++ 11. – Rakete1111
Lỗi biên dịch của bạn là từ ví dụ thứ hai, nhưng câu hỏi của bạn làm cho nó có vẻ giống như nó từ lần đầu tiên của bạn. – Barry