Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  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.

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading