c++ - Linux 编译错误-无法将类型 ‘string’ 转换为类型 ‘string&&’

标签 c++

Linux 编译错误 - 插入包含字符串的映射时,无法将类型“字符串”转换为类型“字符串&&”。在 Windows 上构建良好也是如此。 我的用例:

void insertIf(std::string str1, int value, std::map<std::string,int> &myMap) const
{
    if(value == 1)
    {
        myMap.insert(std::make_pair<std::string, int>(str1, value));       
    }
}

最佳答案

那是因为 std::make_pair 将转发引用作为参数。当您想要显式指定模板参数时,您应该使用带有推导上下文的 std::make_pairstd::pair 的构造函数。

这是您的选择:

配对:

void insertIf(std::string str1, int value, std::map<std::string,int>& myMap) {
    if(value == 1 {
        myMap.insert(std::make_pair(str1, value));
    }
}

对构造函数

void insertIf(std::string str1, int value, std::map<std::string,int>& myMap) {
    if(value == 1 {
        myMap.insert(std::pair<std::string, int>(str1, value));
    }
}

更好的是,emplace:

void insertIf(std::string str1, int value, std::map<std::string,int>& myMap) {
    if(value == 1 {
        myMap.emplace(str1, value);
    }
}

如果你真的想使用带有显式参数的std::make_pair,你可以在模板参数中指定值类别但我建议你不要这样做,它有点违背了 std::make_pair 的全部目的:

void insertIf(std::string str1, int value, std::map<std::string,int>& myMap) {
    if(value == 1 {
        myMap.insert(std::make_pair<std::string&, int&>(str1, value));
    }
}

编辑:它适用于 Windows,因为您必须使用过时版本的 VS,它尚不支持转发引用。

关于c++ - Linux 编译错误-无法将类型 ‘string’ 转换为类型 ‘string&&’,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41469672/

相关文章:

c++ - 使用模板实现双端队列的问题

c++ - 将正在运行的线程中的函数移动到新线程?

c++ - 在使用 NaCl 的 C++ 中,如何按值对 JSON 对象进行排序?

c++ - 如何将可变数量的参数传递给 lambda 函数

c++ - 结构类似于优先级队列,但具有类似下限的结构

c++ - "array bound is not an integer constant before ' ] ' token"使用多个文件时

c++ - 下载文件前如何获取文件名

c++ - 我应该使用仅 header 类还是 lib 文件?

c++ - 有人可以打破这条线 gcc -E -dM - </dev/null

c++ - 我的代码如何区分编译时常量和变量?