0

I have this piece of code and I do not understand why do not works.
During the compilation, in the lines where I call run(), I get:
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 &)'

this is the code:

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;
  
}
thewoz
  • 499
  • 2
  • 4
  • 23

1 Answers1

3

Third argument to function run is declared to be std::function<double(const T &, const T &)>, however you pass a pointer to scoreValue1 causing type deduction to be impossible. In order to deal with this problem you need to either

  1. declare argument to be a pointer to function
void run
(
    const std::vector<T> & dataA
,   const std::vector<T> & dataB
,   double (* function )(const T & a, const T & b)
)

online compiler

  1. Put T of third argument into non-deducible context:
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

user7860670
  • 35,849
  • 4
  • 58
  • 84
  • Importantly, each place `T` should be deduced is considered independantly, and there isn't a **unique** deduction of `T` for the function argument – Caleth Sep 01 '21 at 10:45
  • 3. use explicit template param `run(...)`. But 2 is the best imo. – bolov Sep 01 '21 at 11:07