C++: Constructing std::function from templated method

105 views Asked by At

So, I was trying to get this working:

#include <iostream>
#include <functional>

using namespace std;

class X {
    public:
    template<typename T>
    void f(T t) {
        cout << t << endl;
    }
};

int main() {
    X xx;
    xx.f(5);
    function<void(int)> ff(&X::f);
    return 0;
}

Compiler complains that X::f is <unresolved overloaded function type>, which makes sense. Now, my questions is: how do I tell the compiler which template parameters to use? I essentially want something like

&X::template<int> f

(the equivalent of dot-template for object methods). Any help would be much appreciated.

1

There are 1 answers

1
Billy ONeal On BEST ANSWER

You would need:

function<void(X, int)> ff(&X::f<int>)
ff(xx, 5);

because you asked for a non-static member function meaning you need to provide the instance on which the function is invoked to std::function. For example: http://ideone.com/dYadxQ

If your member f doesn't actually need an X to operate, you should make it a "free" nonmember function rather than a member function of X.