【发布时间】:2017-02-16 08:25:19
【问题描述】:
我有几个std::unordered_maps。他们都有一个std::string 作为他们的密钥,他们的数据不同。我想从给定地图的键中创建一个 csv 字符串,因为该数据需要通过线路发送到连接的客户端。目前,我对每个单独的地图都有一个方法。我想让这个通用,我想出了以下内容:
std::string myClass::getCollection(auto& myMap) {
std::vector <std::string> tmpVec;
for ( auto& elem : myMap) {
tmpVec.push_back(elem.first);
}
std::stringstream ss;
for ( auto& elem : tmpVec ) {
ss << elem <<',';
}
std::string result=ss.str();
result.pop_back(); //remove the last ','
return result;
}
我使用 eclipse 使用 gcc 6.1.0 和 -std=c++14 进行编译,它可以编译但没有链接。
链接器抱怨对std::__cxx11::getCollection(someMap);的未定义引用
无论地图数据和我如何称呼它,它总是告诉我:
Invalid arguments ' Candidates are: std::__cxx11::basic_string<char,std::char_traits<char>,std::allocator<char>> getCollection() '
我该如何解决这个问题?
【问题讨论】:
-
std::string myClass::getCollection(auto& myMap)不是有效的语法。具体来说,auto不是成员函数的有效参数类型。 -
"我认为在 c++14 中可以使用 auto 作为参数..." 仅适用于 lambdas。 “那么我试图用另一种方法来完成吗?”是的,只需使用普通模板:
template<typename MapT> std::string myClass::getCollection(MapT& myMap) -
在函数参数中使用
auto目前是非标准的,但可能会进入 C++20 中的语言。它被称为“缩写函数模板”,我认为它是概念提案的一部分。 GCC 目前将其作为扩展提供;如果你用-pedantic编译它会失败。 -
因为'auto'参数就像一个模板参数,你应该在头文件中定义(不仅仅是声明)成员函数 - 否则定义不会在某些翻译单元中被实例化。
-
缺少minimal reproducible example 链接错误...
标签: c++ parameters c++14 auto