我有这个简单的lambda:
std::variant<int, char> myLambda = []() { // no suitable user-defined conversion from "type" to "std::variant<int, char>" exists
std::variant<int, char> res;
if (true)
{
res = 1;
}
else
{
res = 'c';
}
return res;
};
但是它无法编译,产生错误no suitable user-defined conversion from "type" to "std::variant<int, char>" exists
。我在做什么错了?
答案 0 :(得分:7)
你的意思是
std::variant<int, char> v = []() {
std::variant<int, char> res;
if (true)
{
res = 1;
}
else
{
res = 'c';
}
return res;
}();
^^^
或者你的意思
auto myLambda = []() {
std::variant<int, char> res;
if (true)
{
res = 1;
}
else
{
res = 'c';
}
return res;
};
Lambda表达式具有唯一的类型。
答案 1 :(得分:6)
lambda表达式类型错误。您正在尝试绑定到std::variant<int, char>
。 Lambda表达式类型为ClosureType
。使用auto
:
auto processProjectFile = []() {
std::variant<int, char> res;
if (true) {
res = 1;
} else {
res = 'c';
}
return res;
};
(可选)您可以将ClosureType
强制转换为std::function
,而将auto
替换为std::function<std::variant<int, char>(void)>
。
但是,如果您打算调用lambda,只需将};
最后替换为}();
。