[英]C++14 using auto keyword in a method's definition
我有幾個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);
未定義引用std::__cxx11::getCollection(someMap);
無論地圖數據和我稱之為的方式,它總是告訴我:
Invalid arguments ' Candidates are: std::__cxx11::basic_string<char,std::char_traits<char>,std::allocator<char>> getCollection() '
我該如何解決這個問題?
與在C ++中一樣, auto
參數只允許在lambda中使用(根據@ ildjarn的注釋),你可以開發一個在地圖類型上模板化的函數模板 ,例如:
#include <sstream>
#include <string>
#include <vector>
class myClass {
...
template <typename MapType>
std::string getCollection(const MapType& myMap) {
std::vector <std::string> tmpVec;
for ( const auto& elem : myMap) {
tmpVec.push_back(elem.first);
}
std::stringstream ss;
for ( const auto& elem : tmpVec ) {
ss << elem <<',';
}
std::string result=ss.str();
result.pop_back(); //remove the last ','
return result;
}
還要注意添加const
一些常量 -correctness。
此外,為什么不直接使用字符串流對象構建輸出字符串,而不填充中間 vector<string>
(這是更多代碼,更容易出錯,更多開銷,效率更低)?
而且,由於您只對使用字符串流作為輸出流感興趣,因此使用ostringstream
而不是stringstream
會更好,因為它更有效並且可以更好地傳達您的意圖。
#include <sstream> // for std::ostringstream
#include <string> // for std::string
...
template <typename MapType>
std::string getCollection(const MapType& myMap) {
std::ostringstream ss;
for (const auto& elem : myMap) {
ss << elem.first << ',';
}
std::string result = ss.str();
result.pop_back(); // remove the last ','
return result;
}
為什么不使用模板?
template <typename TMap>
std::string myClass::GetCollection(TMap &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;
}
您的方法完全相同,但我們使用模板函數語法來處理類型推斷,而不是auto
關鍵字。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.