如何指定一个重载函数的指针? [英] How do I specify a pointer to an overloaded function?
问题描述
我想传递一个重载函数到 std :: for_each()
算法。例如,
I want to pass an overloaded function to the std::for_each()
algorithm. For example,
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 $ c>由迭代器类型。显然,它(GCC 4.1.2)不这样做。那么,如何指定
f()
我想要什么?
I'd expect the compiler to resolve f()
by the iterator type. Apparently, it (GCC 4.1.2) doesn't do it. So, how can I specify which f()
I want?
推荐答案
您可以使用 static_cast<>()
指定要根据函数签名使用的 f
函数指针类型:
You can use static_cast<>()
to specify which f
to use according to the function signature implied by the function pointer type:
// 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));
或者,您也可以这样做:
Or, you can also do this:
// 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
如果 f
那么您需要使用 mem_fun
,或对于您的情况,请使用 Dobb博士的文章中提供的解决方案。
If f
is a member function, then you need to use mem_fun
, or for your case, use the solution presented in this Dr. Dobb's article.
这篇关于如何指定一个重载函数的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!