将函数对象作为函数参数传递

Passing a function object as function argument

本文关键字:函数 参数传递 对象      更新时间:2023-10-16

我想以多种方式将我的初始函数对象传递给我自己的函数。

我没有找到任何具有" for_each"功能的示例,但据我所知,它应该以相同的方式工作。

void    f(int& n, void (*g)(int& m) ){ g(n);};
class TEST{
public:
    int init=0;
    TEST(int _init):init(_init){}
    void    operator() (int& m) {m+=init;}
};
int main(int argc, char *argv[])
{
    int k, m;
    cin >> k >> m;
    TEST    mytest(m); // OK, creates object with initialization
    mytest(m);         // OK, using initialized object's "operator()"
    f(k,mytest);       //  error: cannot convert 'TEST' to
                       //  'void (*)(int&)' for argument '2'to
                       //  'void f(int&, void (*)(int&))'
    f(k,TEST(m));      //  error: cannot convert 'TEST' to
                       //  'void (*)(int&)' for argument '2'to
                       //  'void f(int&, void (*)(int&))'
    return 0;
}

类型void (*)(int& m)的函数指针与TEST的实例?

它们可召唤, int&类型。

有什么区别?

它们是两种不同的类型。除非您使用函数模板,否则不能互换使用它们。

因此,解决方案是使用函数模板。

template <typename Callable>
void f(int& n, Callable c )
{
   c(n);
}