-->

推断出的std ::函数调用签名模板参数推断出的std ::函数调用签名模板参数(Deduce te

2019-06-02 12:31发布

考虑使用这个功能:

template<typename ReturnT>
ReturnT foo(const std::function<ReturnT ()>& fun)
{
    return fun();
}

为什么不是可能的编译器来推断ReturnT从通过调用签名?

bool bar() { /* ... */ }

foo<bool>(bar); // works
foo(bar); // error: no matching function call

Answer 1:

std::function<bool()> bar;

foo(bar); // works just fine

C ++不能推断出你的函数的返回类型bar ,因为它必须知道的类型,才能够找到所有你需要的函数指针的构造函数。

例如,谁又能说std::function<std::string()>没有一个构造函数取bool (*)()



Answer 2:

类型的函数指针bool (*)()可被转化为std::function<bool()> ,但不是相同的类型,因此需要的转化率。 之前,编译器检查转换是否可能需要推断ReturnTbool ,但要做到这一点,它需要已经知道std::function<bool()>是一个可能的转换,这是不可能的,直到它演绎ReturnT ......看这个问题?

此外,考虑到bool(*)()也可以转换为std::function<void()>std::function<int()> ...这应该可以推断?

考虑这样的简化:

template<typename T>
  struct function
  {
    template<typename U>
      function(U) { }
  };

template<typename T>
  void foo(function<T>)
  { }

int main()
{
    foo(1);
}

编译器如何知道你是否想创建function<int>function<char>function<void>时,他们都可以从构建int



Answer 3:

功能bar的类型是bool (*)()左右,即:一个正常的预C ++ 11函数类型。 我并不在C ++ 11有信心,但我想,编译器不看到之间的连接bool (*)()const std::function<ReturnT()>&即使当第一可隐式转换到第二对ReturnT = bool



文章来源: Deduce template argument from std::function call signature