首页 > C++11中的函数声明问题

C++11中的函数声明问题

在看C++.Programming.Language.4th.Edition.2013,在307页中间,也就是12.1.2小节的末尾,有这样一个声明:

If you feel inclined to give readers a headache, you may write something like:

struct S {
    [[noreturn]] virtual inline auto f(const unsigned long int *const) -> void const noexcept;
};

果然头疼,请问函数f中的->如何理解?多谢!


这是 C++11 中一种将返回值类型后置的语法,使用时,在原返回值处用 auto 来占位,然后在参数列表后用 -> 来给出返回值类型。

至于这个语法存在的必要性,可以看这样一个例子:

template< typename LHS, typename RHS> 
  auto AddingFunc(const LHS &lhs, const RHS &rhs) -> decltype(lhs+rhs) {return lhs + rhs;}

在这里,因为返回值是两个模版参数的"和",而 C++ 又允许重载加法运算符,所以我们不可能预先知道返回值的类型,需要用 decltype 进行推导。
但是如果把返回值类型 decltype(lhs+rhs) 放在前面的话,会因为 lhs 和 rhs 这两个标识符没有声明而报错,因为这两个标识符是在后面的参数列表中才被声明的。所以在这个例子里,返回值必须后置。

【热门文章】
【热门文章】