Benjamin Barrois
Benjamin Barrois

Reputation: 2686

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?

In my main I can instanciate an object of type std::function<int(int,int)>, so what is the difference? Are their special restrictions with std::function?

Upvotes: 0

Views: 70

Answers (1)

Jaa-c
Jaa-c

Reputation: 5137

Your syntax is wrong. In definition template<class R, class... Args> class CallBack - R matches int(int,int) and Args... is empty.

You would have to do something like this, if you want exactly this signature of CallBack:

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

Upvotes: 2

Related Questions