C++ STL 101:重载功能导致构建错误

Sid*_*jal 4 c++ stl

如果我不重载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;
}
Run Code Online (Sandbox Code Playgroud)

for_each调用都会重复以下构建错误.

错误C2914:'std :: for_each':无法推断模板参数,因为函数参数是模糊错误C2784:'_ _ Fn1 std :: for_each(_InIt,_InIt,_Fn1)':无法从'std:推断'_InIt'的模板参数: :_Vector_iterator <_Ty,_Alloc>".

如果我不重载myfunc,它确实有效.有人解释这里发生了什么.

TIA

Geo*_*che 10

在该上下文中,编译器无法解决重载.std::for_each()期望F它的仿函数有一些任意类型,而不是某些特定的函数类型,因此myFunc这里的重载是模糊的.

您可以明确选择要使用的重载:

std::for_each( v.begin(), v.end(), (void (*)(int))myfunc);
std::for_each( s.begin(), s.end(), (void (*)(std::string))myfunc);
Run Code Online (Sandbox Code Playgroud)

替代方案(最后两个来自评论):

typedef void (*IntFunc)(int);
std::for_each(/*...*/, (IntFunc)myfunc);

typedef void IntFunc(int);
std::for_each(/*...*/, static_cast<IntFunc*>(&myFunc));

// using identity (e.g. from boost or C++0x):
std::for_each(/*...*/, (identity<void(int)>::type*)myfunc);
Run Code Online (Sandbox Code Playgroud)