c++ - 无法使用 std::map 推断 lambda 的返回类型

标签 c++ c++11 lambda

这是一个奇怪的案例。

  • 以下代码在使用用户定义类型时会产生错误,但在使用原语时不会!
  • 使用 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/

相关文章:

c++ - cvSetImageROI 使用灰度和彩色图像

c++ - C 与模块系统

C++ 命名管道客户端不会读取超过 4096 字节

qt - QSplitter - 隐藏拆分器部分中包含的元素时,调整该部分的大小以仅适合可见内容

c# - 为 LINQ/Lambda 创建 OrderBy 表达式

python - 在小于 O(n) 的时间内找到小于给定数字的斐波那契和

c++ - 快速加倍查找斐波那契数,函数在 C++ 中不起作用

c++ - C++ 中编译时生成的 block

c++ - std::thread 在无限循环中的随机时间后锁定

haskell -\in Haskell 标识符的含义