aalbatross
aalbatross

Reputation: 117

How to infer return type of function returned from a function in c++

Consider this code

template <typename OUT>
auto fun(const int& x) {
  return [&](function<OUT(int)> fout) -> decltype(fout(x)) {return fout(x);};
}

calling function

auto w = fun(23)([](const auto& x) {return x*2;});

The function fun when called cannot deduce the return type as above code fails compilation with an error saying that "candidate template ignored: couldn't infer template argument 'OUT'". However when explicitly provided output type this works.

  1. Please help me with the appropriate decltype declaration for my returning function inside fun function so that the callee can automatically deduce the return type.

  2. Also help me with reference materials that I can refer to debug the compiler auto deduction.

Upvotes: 2

Views: 457

Answers (1)

tkausl
tkausl

Reputation: 14279

Given this code:

template <typename OUT>
auto fun(const int& x) {
  return [&](function<OUT(int)> fout) -> decltype(fout(x)) {return fout(x);};
}

it is impossible to deduce OUT because it is impossible to know what OUT could be when calling fun(0). Your lambda needs to be the template, not the outer function.

auto fun(const int& x) {
  return [x](auto&& fout) { return std::forward<decltype(fout)>(fout)(x); };
}

Godbolt

Upvotes: 1

Related Questions