search

Home  >  Q&A  >  body text

c++14 - C++11/14 有什么技巧能在函数内部获取返回类型么?

大家讲道理大家讲道理2767 days ago546

reply all(7)I'll reply

  • 大家讲道理

    大家讲道理2017-04-17 13:27:35

    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.

    reply
    0
  • 迷茫

    迷茫2017-04-17 13:27:35

    auto, decltype

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-17 13:27:35

    This way

    decltype(fun())

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-17 13:27:35

    std::result_of

    reply
    0
  • 阿神

    阿神2017-04-17 13:27:35

    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

    reply
    0
  • 怪我咯

    怪我咯2017-04-17 13:27:35

    auto fn() -> decltype(expression)
    {

       return expression

    }

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-17 13:27:35

    Use decltype

    reply
    0
  • Cancelreply