这是一个奇怪的案例。
- 以下代码在使用用户定义类型时会产生错误,但在使用原语时不会!
- 使用 std::map(也称为 QMap)会产生错误,但如果替换为 std::pair (也称为 QPair)则不会产生错误!
为什么?
我正在使用 MSVC 2013。
class Class {};
typedef double Type; // This works fine
//typedef Class Type; // This produces error
template<typename T, typename ValueFunctor>
std::map<int, typename std::result_of<ValueFunctor(T)>::type >
testFun(ValueFunctor valueFunctor)
{
std::map<int, typename std::result_of<ValueFunctor(T)>::type > map;
return map;
}
void test()
{
std::map<int,Type> output = testFun<Type>(
// The error can be removed by explicitly specifying return type
[](const Type &pair)/*->T2*/{
return pair;
}
);
}
最佳答案
这里发生的事情是,在 MSVC 2013 及更早版本中,std::result_of 模板返回一个 const Class
。而不仅仅是 Class
.这导致 map 的值类型不可复制。
通过更改 typedef double Type
可以看到完全相同的问题至 typedef const double Type
.
如果您仍然必须使用非 C++11 兼容的库,您可以将 lambda 的返回类型指定为 Type
但这需要一份拷贝。
或者,删除常量但改变:
typename std::result_of<ValueFunctor(T)>::type
到
typename std::remove_const<typename std::result_of<ValueFunctor(T)>::type >::type
template<typename T, typename ValueFunctor>
std::map<int, typename std::remove_const<typename std::result_of<ValueFunctor(T)>::type >::type>
testFun(ValueFunctor valueFunctor)
{
std::map<int, typename std::remove_const<typename std::result_of<ValueFunctor(T)>::type>::type > map;
return map;
}
关于c++ - 无法使用 std::map 推断 lambda 的返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41433771/