peter
peter

Reputation: 21

how to infer the return value type from std::function?

I'd like to make the return value type generic using std::function, but it does not work, code: debuggable code can be found: http://cpp.sh/5bk5

class Test
{
public:
  template <typename R, typename F = std::function<R()>>
  R f(F&& op) {
     op();
  }

  void t() {
    int a = 10;
    f([this, a]() { return "chars"; });
  }
};

int main()
{
   t::Test test;
   test.t();
   return 0;
}

Upvotes: 2

Views: 1097

Answers (1)

max66
max66

Reputation: 66230

You could avoid the Template/std::function way and use auto for return type.

If you can compile C++14 it's easy

// Example program
#include <iostream>

class Test
 {
   public:
      Test(){ }

      template <typename F>
      auto f (F && op)
       { return op(); }

      void t()
       { std::cout << f([this]() { return "chars"; }) << std::endl; }
 };


int main()
 {
    Test test;

    test.t();

    return 0;
 }

If you can compile only C++11 you have to use decltype() for Test::f()

  template <typename F>
  auto f (F && op) -> decltype( op() )
   { return op(); }

Upvotes: 2

Related Questions