mercredi 2 décembre 2020

Compilation error when instantiating templated std::function

I want to pass a functor that accepts a templated argument to a templated function. Something like this:

// Generic translator
template <typename T>
int foo(T arg, std::function<int(T)> translate) {
  return translate(arg);
}

// Concrete translator
int chartoint(char c) {
  return static_cast<int>(c);
}

// Call site
void main() {
  foo('p', chartoint); // compilation error here
}

I get Candidate template ignored: could not match 'function<int (type-parameter-0-0)>' against 'int (*)(char)' error.

  1. Why doesn't it work?
  2. How to make it work?

Thanks!

EDIT: This works for some reason:

void main() {
  std::function<int(char)> chartoint_local = chartoint;
  foo('p', chartoint_local); // Works.
}

The original questions still stand. If I could do this without extra variable would be happy.

Aucun commentaire:

Enregistrer un commentaire