可调用结果类型的扣除

abr*_*ert 5 c++ callable type-deduction c++14

我尝试推断可调用模板参数的类型,不幸的是没有成功:

template<typename callable, typename T_out >
class A
{};

template<typename callable>
auto make_A( callable f )
{
  return A<callable, typename std::result_of_t<callable> >{ f };
}

int main()
{
  make_A( []( float f ){ return f;} );
}
Run Code Online (Sandbox Code Playgroud)

上面的代码导致以下错误:

error: implicit instantiation of undefined template 'std::__1::result_of<(lambda at /Users/arirasch/WWU/dev/xcode/tests/tests/main.cpp:31:11)>'
template <class _Tp> using result_of_t = typename result_of<_Tp>::type;
Run Code Online (Sandbox Code Playgroud)

有谁知道如何修理它?

提前谢谢了。

krz*_*zaq 2

您需要将参数列表传递给std::result_of,否则无法判断返回类型(operator()毕竟可以重载)。

return A<callable, std::result_of_t<callable(float)> >{ f }
Run Code Online (Sandbox Code Playgroud)

(前提A<callable, std::result_of_t<callable(float)>是可以用 构造f,但示例中并非如此)