将函子传递给 C++ 中的构造函数

passing a functor to a constructor in C++

本文关键字:C++ 构造函数      更新时间:2023-10-16

这是否可以帮助我传递函子,例如:

struct BFunc
{
    double operator()(const double x, const double y, const double z){
        return 0.1;
        }
};

到类的构造函数:

class foo
{
    int n;
public:
foo();
foo(int nn, &bfunc):n(nn),f(func()){        
    } 
double getResult(double x){
        return f(x);
    }   
}

谢谢

谢谢大家的快速回复。我通过将函子类型的变量声明为波纹管来解决它。但我想知道没有这个是否有可能做到这一点。关键是我想创建一个类,我将其作为边界条件和范围传递给它,因此它创建了一个 2D 或 3D 坐标矩阵,该矩阵为内部所有点为零,外部所有点为零。我想让它尽可能普遍。最终我最终遵循以下方法。

using namespace std;
struct functor {
    int a=11;
    int operator () (int x) const {
    cout << a << endl;
    return 2*x;
    }
};
class myclass {
    int y=0;
    functor af;// ** I did not wanted to have this line and make it generic  **  //
public:
    template <typename F> myclass(const F & f):af(f){
        //af=f;//auto af(f);
        y=f(5);
        cout<<"y is"<<y<<endl;
        int z=af(5);
        cout<<"z is"<<z<<endl;
        cout<<"    why   "<<typeid(af).name()<<endl;
    }
    int getFuncX(int x){
        int y=af(x);
        return y;
    }

};
int main(int argc, char **argv) {
    functor f = {5};
    myclass c(f);
    cout<<" See What happens:  "<<c.getFuncX(71)<<endl;
    return 0;
}

对不起,如果它很乱!正如你所猜到的,我是一个初学者。谢谢