问题描述
我想将重载函数传递给 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().显然,它(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,或者对于您的情况,请使用 本博士中提出的解决方案. 多布的文章.
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.
这篇关于如何指定指向重载函数的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)