C++ STL 101: Overload function causes build error
- by Sidjal
Trivial code that works if I do not overload myfunc.
void myfunc(int i)
{
std::cout << "calling myfunc with arg " << i << std::endl;
}
void myfunc(std::string s)
{
std::cout << "calling myfunc with arg " << s << std::endl;
}
void testalgos()
{
std::vector<int> v;
v.push_back(1);
v.push_back(2);
std::vector<std::string> s;
s.push_back("one");
s.push_back("two");
std::for_each( v.begin(), v.end(), myfunc);
std::for_each( s.begin(), s.end(), myfunc);
return;
}
int _tmain(int argc, _TCHAR* argv[])
{
std::cout << "Hello World" << std::endl;
testalgos();
return 0;
}
The following build errors repeat for both for_each calls.
error C2914: 'std::for_each' : cannot deduce template argument as function argument is ambiguous
error C2784: '_Fn1 std::for_each(_InIt,_InIt,_Fn1)' : could not deduce template argument for '_InIt' from 'std::_Vector_iterator<_Ty,_Alloc'.
It does work if I do not overload myfunc.Can someone explain what is happening here.
TIA