c++14 - C++11/14 有什么技巧能在函数内部获取返回类型么?
大家讲道理
大家讲道理 2017-04-17 13:25:35
0
7
576
大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all(7)
大家讲道理

I don’t agree with @Sunmingqi’s point of view. We now simplify the problem into four situations:

  • Directly specified function type... I have not found that C++ has the ability to change the return type of a function declaration midway. Just write the return type directly. Writing decltype(fn()) only adds trouble.

  • Function template, and the return type is a template parameter. There is no need to "dynamically obtain", just use T, U and the like.

  • Function template, but the return type is determined by another operator. Consider the following example:

template <typename T, typename U>
auto fn(T a, U b) { return a + b; }

Obviously, auto == decltype(a + b) here, so we can still directly specify the type of the variable as decltype(a + b).

  • lambda. There is no difference in this. Anyway, lambda is the operator() of anonymous class, and the return value must be one of the above three.

To sum up, I don’t think there are any types in C++ that require “dynamic acquisition”. Everything must be determined, after all, it is strongly typed.

迷茫

auto, decltype

Peter_Zhu

This way

decltype(fun())
巴扎黑

std::result_of

阿神

Dynamic acquisition? Impossible, C++ does not have reflection (except RTTI)
The decltype and std::result_of mentioned in other answers are both static and are determined at compile time, which should also meet your requirements

刘奇

auto fn() -> decltype(expression)
{

   return expression

}

巴扎黑

Use decltype

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template