【问题标题】:Can the return type of the function be obtained from within the function?函数的返回类型可以从函数内部获取吗?
【发布时间】:2019-02-10 22:09:55
【问题描述】:

函数的返回类型可以在函数内部通过简单的方式获取吗?

例如,给定:

template <typename P>
static inline auto foo(P p) -> typename std::remove_reference<decltype(*p)>::type {
    typename std::remove_reference<decltype(*p)>::type f{};  // <-- here

    ...
}

在 C++11 中,我可以在 foo 本身内引用 foo 的大讨厌的返回类型,而不重复它,在标记为 // &lt;-- here 的行处?

【问题讨论】:

  • 在C++14中,可以去掉尾随的返回类型,使用return f;推导出返回类型。

标签: c++ c++11 trailing-return-type


【解决方案1】:

使用decltype 调用函数。

decltype(foo(p)) f{};

【讨论】:

  • decltype 让生活变得轻松;)
猜你喜欢
  • 2011-04-04
  • 1970-01-01
  • 1970-01-01
  • 2020-04-11
  • 1970-01-01
  • 2021-04-13
  • 1970-01-01
  • 2016-07-01
  • 2018-11-06
相关资源
最近更新 更多