确定作为模板化参数给定的函数的返回类型
Determine the return-type of a function which is given as a templated-parameter
我有一个带有模板参数的函数,它接受另一个函数。在该函数中,我想调用一个不同的模板函数,该函数需要使用函数参数的返回类型进行实例化。
由于我可能把最后一段搞砸了,让我举个例子来澄清一下:
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)...))>();
}
对于我尝试过的情况,decltype
和std::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()>
。
相关文章:
- 函数作为模板参数,是否对返回类型强制约束
- 在 c++ 中将函数返回类型指定为模板参数
- C++方法是否可以根据传递给构造函数的参数具有不同的返回类型?
- 基于类型作为参数的字符串表示形式具有不同返回类型的函数
- 具有"templated"返回类型和参数的函数指针
- 如何创建两个具有相同名称和不同返回类型并基于布尔参数运行的函数
- 使用constexpr + auto作为返回和参数类型的奇怪类型推导
- 通过引用传递参数;函数返回类型是否必须为 VOID?
- 有没有办法根据 lambda 参数返回类型部分专用化我的模板化函数?
- 如何定义依赖于参数包转换的函数的返回类型
- 无法推断返回类型的模板参数
- C++模板;作为模板参数传递的函数的自动推导返回类型
- 如何在模板参数中分离函数类型返回类型和参数
- 为什么函数返回类型中不允许参数推导?
- 模板化函数以从输入参数推断返回类型 stl-container
- 将 2D 数组作为函数参数,并返回 2D 数组作为函数的返回类型
- C++ 如何将参数绑定到具有相同返回类型的函数,并将它们全部存储在一个容器中
- 为什么编译器不能从返回类型中推断出模板参数?
- 具有不同模板参数的函数返回类型
- C++:返回类型为 T 的模板函数不带 T 类型参数,将无法编译