我想将重载函数传递给std::for_each()
算法。例如,
class A {
void f(char c);
void f(int i);
void scan(const std::string& s) {
std::for_each(s.begin(), s.end(), f);
}
};
我希望编译器能够解决f()
通过迭代器类型。显然,它(GCC 4.1.2)没有这样做。那么,我如何指定哪个f()
I want?
您可以使用static_cast<>()
指定哪个f
根据函数指针类型隐含的函数签名来使用:
// Uses the void f(char c); overload
std::for_each(s.begin(), s.end(), static_cast<void (*)(char)>(&f));
// Uses the void f(int i); overload
std::for_each(s.begin(), s.end(), static_cast<void (*)(int)>(&f));
或者,您也可以这样做:
// The compiler will figure out which f to use according to
// the function pointer declaration.
void (*fpc)(char) = &f;
std::for_each(s.begin(), s.end(), fpc); // Uses the void f(char c); overload
void (*fpi)(int) = &f;
std::for_each(s.begin(), s.end(), fpi); // Uses the void f(int i); overload
If f
是一个成员函数,那么你需要使用mem_fun http://www.cplusplus.com/reference/std/functional/mem_fun/,或者根据您的情况,使用Dobb 博士的文章中提出的解决方案 http://www.drdobbs.com/184401746.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)