且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么在C ++ 11中需要添加尾随返回类型?

更新时间:2023-11-30 11:19:40

在所有解析完成后,我看不到让decltype执行类型解析的弊端(对于上面的示例来说,这样做很好).

I fail to see a downside to having decltype perform type resolution after all parsing is completed (which would work fine for the above example).

不利之处在于,如果不从根本上改变C ++解析和处理模型的基本基础,这是不可能的.

The downside is that it's not possible without fundamentally altering the basic foundations of the C++ parsing and processing model.

为了执行您建议的操作,编译器将必须查看decltype语法并对该语法的内容进行一些基本的词法分析.然后,它继续解析更多的源文件.在稍后的某个时刻(何时?),它决定执行以下操作:嘿,我之前看过的东西?我现在将为他们进行所有解析工作."

In order to do what you suggest, the compiler will have to see the decltype syntax and do some basic lexical analysis of the contents of the syntax. Then, it goes on to parse more of the source file. At some later point (when?), it decides to go, "hey, that stuff I looked at before? I'm going to do all of the parsing work for them now."

作为一般规则,C ++不支持在符号前定义 . C ++解析框架的基本假设是,如果在使用符号之前未声明该符号,则它是编译器错误.

As a general rule, C++ doesn't support looking ahead for the definition of symbols. The basic assumption of the C++ parsing framework is that, if the symbol is not declared before it is used, it is a compiler error.

班级可以先行一步,但仅限于其成员.这部分是因为它很清楚id表达式何时可以引用成员变量(即:如果它不引用作用域中已声明的局部变量或全局变量).这里不是这种情况,我们不确定id-expression到底指的是什么.

Classes can get away with lookahead, but only with respect to their members. This is in part because its quite clear when an id-expression could be referring to a member variable (ie: if it's not referring to an already declared local or global variable in scope). That's not the case here, where we're not sure what exactly the id-expression could be referring to.

此外,您的建议还会造成歧义.这是什么意思:

Furthermore, what you suggest creates ambiguities. What does this mean:

int lhs;

template<class Lhs, class Rhs>
  decltype(lhs+rhs) adding_func(const Lhs &lhs, const Rhs &rhs);

decltype语法是指全局变量lhs还是局部变量lhs?

Is the decltype syntax refering to the global lhs variable, or the local lhs function parameter?

我们现在的操作方式,这两者之间有明确的界限:

The way we do it now, there's a clear delineation between these two:

int lhs;
float rhs;

template<class Lhs, class Rhs>
  decltype(lhs+rhs) adding_func1(const Lhs &lhs, const Rhs &rhs);
template<class Lhs, class Rhs>
  auto adding_func2(const Lhs &lhs, const Rhs &rhs) -> decltype(lhs+rhs);

adding_func1是指全局变量. adding_func2指的是功能参数.

adding_func1 refers to the global variables. adding_func2 refers to the function parameter.

因此,您可以从根本上破坏每个C ++编译器.或者,您也可以稍后指定返回类型.

So you can either radically break every C++ compiler on the face of the Earth. Or you can simply late-specify your return type.

或者您可以采用C ++ 14方法,而完全说明.

Or you can take the C++14 approach and not bother to state it at all.