确定作为模板化参数给定的函数的返回类型

Determine the return-type of a function which is given as a templated-parameter

本文关键字:返回类型 参数 函数      更新时间:2023-10-16

我有一个带有模板参数的函数,它接受另一个函数。在该函数中,我想调用一个不同的模板函数,该函数需要使用函数参数的返回类型进行实例化。

由于我可能把最后一段搞砸了,让我举个例子来澄清一下:

template <typename funT>
void foo(funT function_to_call)
{
    auto data = bar<funT::return_value>();
    /// do some stuff with data.
    /// call function_to_call, but bar needed to be called first.
}

如何获取funT::return_value?

非常感谢,

您可以通过以下方式在特定的std::result_of中使用类型特征:

template <typename funT>
void foo(funT function_to_call) {
  auto data = bar<typename std::result_of<decltype(function_to_call)&()>::type>();
  //...
}

现场演示

您还可以通过以下方式使用可变模板来进一步泛化以接受任何类型的函数及其输入参数:

template <typename funT, typename ...Args>
void foo(funT function_to_call, Args... args) {
  auto data = bar<typename std::result_of<funT(Args...)>::type>();
  ...
}

现场演示

除了像其他人建议的那样使用result_of,您还可以使用decltype

对于function_to_call不接受任何参数的情况,可以执行以下操作:

auto data = bar<decltype(function_to_call())>();

然而,对于更通用的情况,正如@101010所指出的,您可以让函数接受任意数量的参数。生成的代码如下所示:

template <typename funT, typename ...Args>
void foo(funT function_to_call, Args&&... args) 
{
   auto data = bar<decltype(function_to_call(std::forward<Args>(args)...))>();
}

对于我尝试过的情况,decltypestd::result_of在返回正确类型方面具有相同的功能,如果传递的函数类型不是指向成员的指针,如@hvd所指出的。纵观g++源,对于上述情况,std::result_of通常根据decltype来实现。

尽管C++14 std::result_of_t选项也很有吸引力,但使用它似乎比typename std::result_of<...>::type选项更干净、更易读。

您可以使用typename std::result_of<funT()>::type来满足您的需求,如果您可以访问C++14,则可以使用std::result_of_t<funT()>