C ++:从模板化方法构造std :: function

时间:2014-11-10 23:19:20

标签: c++ templates c++11 std std-function

所以,我试图让这个工作:

#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;
}

编译器抱怨X::f<unresolved overloaded function type>,这是有道理的。现在,我的问题是:如何告诉编译器使用哪些模板参数?我基本上想要像

这样的东西
&X::template<int> f

(相当于对象方法的点模板)。任何帮助将非常感激。

1 个答案:

答案 0 :(得分:3)

你需要:

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

因为您要求提供非静态成员函数,这意味着您需要将调用该函数的实例提供给std::function。例如:http://ideone.com/dYadxQ

如果您的会员f实际上并不需要X进行操作,那么您应该将其设为&#34;免费&#34;非成员函数而不是X的成员函数。