gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 11:34:00 25 4
gpt4 key购买 nike

我想将重载函数传递给 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() 呢?

最佳答案

您可以使用 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

如果 f是成员函数,则需要使用 mem_fun ,或者对于您的情况,请使用 the solution presented in this Dr. Dobb's article .

关于c++ - 如何指定指向重载函数的指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2942426/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com