c++ - How to re-write templated function to handle type deduction -
so, have search function map container:
template <typename key, typename t> void searchinmapbykey(std::map<key,t> map, t keyvalue) { if(map.empty()) { std::cout << "map empty, nothing search for..." << "\n"; } else { for(const auto & element : map) { if(element.first==keyvalue) { std::cout << keyvalue << "matches key value " << " in map" << "\n"; } } } }
and seem running deducing type issues, error:
candidate template ignored: deduced conflicting types parameter 't' ('std::__1::basic_string<char>' vs. 'int')
when try test following code:
map<int,string> mymap; mymap.emplace(1,string("a")); mymap.emplace(2,string("b")); mymap.emplace(3,string("c")); searchinmapbykey(mymap,1);
because compiler doesn't know type associate "t", integer or string.
now, asked similar question same type of error , able solve issue using c++ style strings. however, don't want keep handling conflicting type deduction errors on case case basis, , wondering how write function (using templates) compiler better deduce type should associated "t" outset?
the problem mismatch between type of map , key types. fix not correcting order of parameters std::map
argument, changing definition more generic.
template <typename maptype, typename keytype> void searchinmapbykey(const maptype & map, keytype key) { if(map.empty()) { std::cout << "map empty, nothing search for..." << "\n"; return; } for(const auto & element : map) { if(element.first==keyvalue) { std::cout << keyvalue << "matches key value " << " in map" << "\n"; } } }
Comments
Post a Comment