【问题标题】:Calling one templated function isn't working [duplicate]调用一个模板函数不起作用[重复]
【发布时间】:2014-06-20 19:59:51
【问题描述】:

我不知道如何调用函数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'

【问题讨论】:

  • @sp2danny 我怀疑英文单词的选择给这个问题带来了一定的气味。正在修复...

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


【解决方案1】:

您不能像这样将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.); //!
}

【讨论】:

  • 可以从函数转换为std::function。您链接到有关强制转换 成员函数 的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-08-18
  • 1970-01-01
  • 2021-04-02
  • 2019-11-24
  • 2019-01-24
  • 2018-07-22
  • 2015-09-30
相关资源
最近更新 更多