我有一个函数,我想让变量返回计算值从函数的返回类型自动推导出来.
我已经看到Decltype返回成员函数的函数,我知道decltype(func()) var我可以得到返回类型.但这只适用于没有参数的函数.如果我有一个参数,我必须decltype(func(/* some dummy value convertible to argument type*/))得到返回类型.
是否有任何方法可以执行上述操作而无需指定虚拟值?
auto func(int a) -> std::deque<decltype(a)> {
// lots of code
/* ideally */
decltype(func)::return_type result;
/* fill result*/
return result;
}
Run Code Online (Sandbox Code Playgroud)
您需要指定参数类型,因为不同的重载可以具有不同的返回类型.
您可以使用declval以下命令指定伪参数:
#include <utility>
decltype(func(std::declval<ArgType>())) result;
Run Code Online (Sandbox Code Playgroud)
或者您可以通过使用类型特征避免给出虚拟值:
#include <type_traits>
std::result_of<decltype(func), ArgType>::type result;
Run Code Online (Sandbox Code Playgroud)