繁体   English   中英

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

[英]C++ STL 101: Overload function causes build error

如果我不重载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;
}

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

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

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

TIA

在该上下文中,编译器无法解决重载。 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);

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

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);

编译器无法推断出类型的仿函数。 你可以制作你的功能模板:

template<typename T> void myfunc(T);

template<> void myfunc(int i)
{
    std::cout << "calling myfunc with arg " << i << std::endl;
}
template<> void myfunc(std::string s)
{
    std::cout << "calling myfunc with arg " << s << std::endl;
}

然后使用如下:

std::for_each( v.begin(), v.end(), myfunc<int>);
std::for_each( s.begin(), s.end(), myfunc<std::string>);

编译器无法推断使用哪个,因为两个重载都会匹配参数(它不依赖于迭代器的类型)。

除了将参数显式地转换为合适的指针类型之外,另一个选项可能是使用std::ptr_fun辅助函数将其包装在std::ptr_fun函数中,并通过显式提供(部分)来帮助模板推导。

std::for_each( v.begin(), v.end(), std::ptr_fun<int>(myfunc));
std::for_each( s.begin(), s.end(), std::ptr_fun<std::string>(myfunc));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM