C++14 using auto keyword in a method's definition

后端 未结 3 987
不思量自难忘°
不思量自难忘° 2021-02-19 18:46

I have several std::unordered_maps. They all have an std::string as their key and their data differs. I want to make a csv string from a given map\'s k

3条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-19 19:29

    Why not just use a template?

    template 
    std::string myClass::GetCollection(TMap &myMap) {
        std::vector  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;
    }
    

    Your method is exactly the same, but instead of the auto keyword, we use template function syntax to handle the type inference.

提交回复
热议问题