[英]Determine the return-type of a function which is given as a templated-parameter
I have a function with a templated parameter which accepts another function. 我有一个带有模板化参数的函数,它接受另一个函数。 Within that function, I'd like to call a different template function which needs to be instantiated with the return-type of function argument.
在该函数中,我想调用一个不同的模板函数,该函数需要使用函数参数的return类型进行实例化。
Since I probably screwed that last paragraph up, let me attempt to clarify with an example: 由于我可能把最后一段搞砸了,让我试着用一个例子来澄清:
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.
}
How do get funT::return_value ? 怎么得到funT :: return_value?
Many thanks, 非常感谢,
You could use type traits in particular std::result_of
in the following manner: 您可以按以下方式使用特定于
std::result_of
类型特征:
template <typename funT>
void foo(funT function_to_call) {
auto data = bar<typename std::result_of<decltype(function_to_call)&()>::type>();
//...
}
You could also further generalize to accept any kind of function along with its input arguments by using variadic templates in the following manner: 您还可以通过以下方式使用可变参数模板进一步概括接受任何类型的函数及其输入参数:
template <typename funT, typename ...Args>
void foo(funT function_to_call, Args... args) {
auto data = bar<typename std::result_of<funT(Args...)>::type>();
...
}
Apart from using result_of
as others have suggested, you can also use decltype
. 除了使用其他人建议的
result_of
之外,您还可以使用decltype
。
For the case where function_to_call
accepts no parameters, you can do the following: 对于
function_to_call
接受任何参数的情况,您可以执行以下操作:
auto data = bar<decltype(function_to_call())>();
However, for a more generic case, as @101010 has pointed out, you can have your function accept any number of arguments. 但是,对于更通用的情况,正如@ 101010指出的那样,您可以让您的函数接受任意数量的参数。 The resulting code would look like this:
生成的代码如下所示:
template <typename funT, typename ...Args>
void foo(funT function_to_call, Args&&... args)
{
auto data = bar<decltype(function_to_call(std::forward<Args>(args)...))>();
}
For the cases that I've tried, decltype
and std::result_of
have the same functionality with regards to returning the correct type if the function type being passed in isn't a pointer-to-member, as @hvd pointed out. 对于我尝试过的情况,如果传入的函数类型不是指向成员的指针,则
decltype
和std::result_of
在返回正确的类型方面具有相同的功能,如@hvd指出的那样。 Looking looking through the g++ source, std::result_of
is often implemented in terms of decltype
for the case described above. 通过查看g ++源代码,
std::result_of
通常根据上述情况的decltype
实现。
Using this seems much cleaner and more readable to me than the typename std::result_of<...>::type
alternative, although the C++14 std::result_of_t
option is quite attractive as well. 使用它看起来比
typename std::result_of<...>::type
替代方案更清晰,更易读,尽管C ++ 14 std::result_of_t
选项也非常有吸引力。
您可以使用typename std::result_of<funT()>::type
,以满足您的需求,或者std::result_of_t<funT()>
如果你有机会到C ++ 14。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.