如何指定指向重载函数的指针?

2022-01-07 00:00:00 c++ stl

我想将重载函数传递给 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.

相关文章