【问题标题】:Template parameter in std::function [duplicate]std::function 中的模板参数
【发布时间】:2021-10-30 20:33:56
【问题描述】:

我有这段代码,但我不明白为什么不起作用。
在编译期间,在我调用 run() 的行中,我得到:
Candidate template ignored: could not match 'function<double (const type-parameter-0-0 &, const type-parameter-0-0 &)>' against 'double (*)(const data_t &, const data_t &)'

这是代码:

struct data_t {
  double value1;
  double value2;
};

double scoreValue1(const data_t & a, const data_t & b) { return a.value1 - b.value1; }
double scoreValue2(const data_t & a, const data_t & b) { return a.value2 * b.value2; }

template <class T>
void run(const std::vector<T> & dataA, const std::vector<T> & dataB, std::function<double(const T &, const T &)> function) {
  
  double value = 0;
  
  for(size_t i=0; i<dataA.size(); ++i)
    value += function(dataA[i], dataB[i]);
  
    std::cout << value << std::endl;
    
}

int main(int argc, const char * argv[]) {

  std::vector<data_t> dataA;
  std::vector<data_t> dataB;

  run(dataA, dataB, scoreValue1);
  run(dataA, dataB, scoreValue2);

  return 0;
  
}

【问题讨论】:

    标签: c++ templates std-function template-argument-deduction


    【解决方案1】:

    函数run 的第三个参数被声明为std::function&lt;double(const T &amp;, const T &amp;)&gt;,但是你传递一个指向scoreValue1 的指针导致类型推断是不可能的。为了解决这个问题,您需要

    1. 将参数声明为指向函数的指针
    void run
    (
        const std::vector<T> & dataA
    ,   const std::vector<T> & dataB
    ,   double (* function )(const T & a, const T & b)
    )
    

    online compiler

    1. 将第三个参数的T 放入不可演绎的上下文中:
    void run
    (
        const std::vector<T> & dataA
    ,   const std::vector<T> & dataB
    ,   std::function<double(const ::std::type_identity_t<T> &, const ::std::type_identity_t<T> &)> function
    )
    

    online compiler

    【讨论】:

    • 重要的是,T 应该被推导的每个地方都是独立考虑的,并且函数参数没有T唯一推导
    • 3.使用显式模板参数run&lt;data_t&gt;(...)。但是 2 是最好的 imo。
    猜你喜欢
    • 1970-01-01
    • 2014-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-13
    • 1970-01-01
    相关资源
    最近更新 更多