【问题标题】:how to infer the return value type from std::function?如何从 std::function 推断返回值类型?
【发布时间】:2016-12-01 00:38:29
【问题描述】:

我想使用std::function 将返回值类型设为通用,但它不起作用,代码: 可调试代码见: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;
}

【问题讨论】:

  • 也许使用result_of 来获取返回类型?
  • 您是否尝试过使用 void*?这就是拥有泛型类型的 Cish 方式。

标签: c++ c++11 templates lambda template-argument-deduction


【解决方案1】:

您可以避免使用 Template/std::function 方式并使用 auto 作为返回类型。

如果你能编译 C++14 那就简单了

// 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;
 }

如果你只能编译 C++11,你必须使用 decltype() 代替 Test::f()

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多