1

I have a generic code that executes the passsed lambda and checks the outputs. I would like the helper method to be fully deduced, but cannot come up with the solution since the method returns std::optional and I want the processing method to return the underlying type of it. Code:

#include <optional> #include <type_traits> std::optional<int> dummy() { return {42}; }; template<typename F, typename Ret = std::result_of_t<F(void)>> static Ret process(const F& f) { Ret val{}; if(auto res = f(); res) { val = *res;} return val; } int main() { // call auto result = process(&dummy); } 

The result is of course type of std::optional<int>. What should I change in my template definition to deduce the return type of process to underlying type of std::optional - int?

5
  • Please try to copy/paste the code you actually showed in your question, and attempt to compile it. It won't work. Obvious typos. Please show real code in your question. Commented Apr 13, 2020 at 11:35
  • @SamVarshavchik Yop, typo in Ret. Now it compiles. Commented Apr 13, 2020 at 11:37
  • No, it doesn't compile. That's just one of an amazing number of typos and errors, above. You've been on stackoverflow.com for seven years, and you still are not familiar with the requirements for a minimal reproducible example? Commented Apr 13, 2020 at 11:40
  • Well, main added. Commented Apr 13, 2020 at 11:44
  • 1
    @SamVarshavchik What are you talking about, after the Ret typo fix, it was perfectly fine. Commented Apr 13, 2020 at 13:31

1 Answer 1

4

All standard containers keep information about underlying data type on value_type typedef.

Why not write:

template<typename F, typename Ret = typename std::result_of_t<F(void)>::value_type > 

then for optional<int>, Ret is int.

Demo

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.