调用一个模板化函数不起作用

时间:2014-06-20 19:59:51

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

我不知道如何调用函数call

它是一个模板化的类,带有模板化的函数调用。但是我该如何使用这段代码?

#include <iostream>
#include <conio.h>
#include <functional>

template <typename Result> class Imp {
    template <typename ...Args> int call(std::function<Result(Args...)> func, Args... args) {
        return 0;
    }
};

int f(double a, double b) {
    return (int)a+b;
}

int main() {
    Imp<int> a;
    a.call<double, double>(f, 1., 1.); //!
}

error C2784: 'int Imp<int>::call(std::function<Result(Args...)>,Args...)' : could not deduce template argument for 'overloaded function type' from 'overloaded function type'
      with
      [
          Result=int
      ]
       : see declaration of 'Imp<int>::call'

1 个答案:

答案 0 :(得分:0)

您无法将function pointer传递给std::function(请参阅此question

将其更改为:

template <typename Result> class Imp {
public:
    template <class Func,typename ...Args> int call(Func f, Args... args) {
        return 0;
    }
};
int f(double a, double b) {return (int)a+b;}
int main() {
    Imp<int> a;
    a.call(f, 1., 1.); //!
}

ideone

或者:

#include <functional>
template <typename Result> class Imp {
public:
    template <typename ...Args> int call(std::function<Result(Args...)> f, Args... args) {
        return 0;
    }
};
int f(double a, double b) {return (int)a+b;}
int main() {
    Imp<int> a;
    a.call(std::function<int(double,double)>(f), 1., 1.); //!
}