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().显然,它(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.
这篇关于如何指定指向重载函数的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何指定指向重载函数的指针?
基础教程推荐
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- CString 到 char* 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
