I have this template to print out Collection structures but it seems like the function is precompiled with the argument???
If I only do the print statement inside the function, then the if else cases for the type does work, however, if I add different implementation for each case, it tests the argument against every case.
It gives an error before the program run (I think. I could not step through the code even though I put my break point to the start of the program).
Could someone give me a lecture on this please? and how to bypass this problem? Thank you. Appreciate it.
template <typename T>
void print(T& collection)
{
string type = typeid(T).name();
if(type.find("map") != string::npos){
for(auto const& item : collection){
std::cout << item.first << " " << item.second << endl;
}
}
else {
for(auto const& item : collection){
std::cout << item << std::endl;
}
}
}
Here is the error if I call the function with a map:
error: invalid operands to binary expression ('ostream' (aka 'basic_ostream<char>') and 'const std::__1::pair<const std::__1::basic_string<char>, int>')
std::cout << item << std::endl;
Similarly, if called with an array:
error: member reference base type 'const int' is not a structure or union
std::cout << item.first << " " << item.second << endl;