我有一个带有模板化参数的函数,它接受另一个函数。在该函数中,我想调用一个不同的模板函数,该函数需要使用函数参数的return类型进行实例化。
由于我可能把最后一段搞砸了,让我试着用一个例子来澄清:
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?
非常感谢,
答案 0 :(得分:1)
您可以按以下方式使用特定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>();
...
}
答案 1 :(得分:1)
除了使用其他人建议的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
实现。
使用它看起来比typename std::result_of<...>::type
替代方案更清晰,更易读,尽管C ++ 14 std::result_of_t
选项也非常有吸引力。
答案 2 :(得分:0)
您可以使用typename std::result_of<funT()>::type
满足您的需求,或std::result_of_t<funT()>
如果您有权访问C ++ 14。