简体   繁体   English

std :: function可以成为类数据成员吗?

[英]Can std::function be a class data member?

I have the simple following code: 我有简单的以下代码:

template<class R, class... Args> class CallBack {
protected:
    std::function<R(Args...)> myFunc;

public:
    CallBack(std::function<R(Args...)> funcIn) : myFunc(funcIn) {}

    virtual ~CallBack() {}

    R call(Args... args) {
        return myFunc(args...);
    }
};

int main() {
    std::function<int(int,int)> tmp = [](int y, int z){return y + z + 2;};
    CallBack<int(int,int)> x(tmp);
    std::cout << x.call(12, 7);
    return 0;
}

However, it just doesn't work. 但是,它根本不起作用。 I get: 我得到:

../src/main.cpp:17:28: error: function returning a function
  std::function<R(Args...)> myFunc;
                            ^

I checked the prototype of std::function, and it is a simple class, so why couldn't I use it as an attribute for my class CallBack ? 我检查了std :: function的原型,它是一个简单的类,所以为什么不能将其用作我的类CallBack的属性?

In my main I can instanciate an object of type std::function<int(int,int)> , so what is the difference? 在我的主语言中,我可以实例化std::function<int(int,int)>类型的对象,所以有什么区别? Are their special restrictions with std::function ? 它们对std::function特殊限制吗?

Your syntax is wrong. 您的语法错误。 In definition template<class R, class... Args> class CallBack - R matches int(int,int) and Args... is empty. 在定义template<class R, class... Args> class CallBack - R匹配int(int,int)Args...为空。

You would have to do something like this, if you want exactly this signature of CallBack : 如果您确实需要CallBack此签名,则必须执行以下操作:

CallBack<int,int,int> x(tmp);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM