C++ 11支持新的函数语法:
auto func_name(int x, int y) -> int;
Run Code Online (Sandbox Code Playgroud)
目前此函数将声明为:
int func_name(int x, int y);
Run Code Online (Sandbox Code Playgroud)
新风格似乎还没有被广泛采用(比如在gcc stl中)
但是,这种新风格是否应该在新的C++ 11程序中随处可见,还是仅在需要时使用?
就个人而言,我更喜欢旧款式,但是混合风格的代码库看起来很丑陋.
我终于开始阅读c ++ 11了,我不明白为什么需要trailing-return-types.
我遇到了以下示例,用于突出显示问题:
template<class Lhs, class Rhs>
decltype(lhs+rhs) adding_func(const Lhs &lhs, const Rhs &rhs) {return lhs + rhs;}
Run Code Online (Sandbox Code Playgroud)
这个例子是非法的,因为decltype(lhs+rhs)
没有工作,因为标识符lhs
和rhs
仅解析阶段后有效.
我想我的问题是关于decltype
类型解析的时间.如果我没有弄错,关键字decltype
用于在编译时确定表达式的类型.
decltype
在完成所有解析之后,我没有看到执行类型解析的缺点(这对于上面的示例可以正常工作).我相信这将是解决问题的一种更简单的方法......
相反,C++ 11标准提供了trailing-return-types:
template<class Lhs, class Rhs>
auto adding_func(const Lhs &lhs, const Rhs &rhs) -> decltype(lhs+rhs) {return lhs + rhs;}
Run Code Online (Sandbox Code Playgroud)
我毫不怀疑我遗漏了一些东西,因为我没有看到其他使用trailing-return-types.我的推理中的缺陷在哪里?
trailing-return-types对我来说似乎是一个过于复杂的解决方案,因为decltype
在解析完整的函数体之后具有类型解析也可以正常工作?
我看过这个函数,但我不知道这里发生了什么:
template <typename Container>
auto MaxElement(Container &c,int num_of_el)->decltype(c[0]){
int index=0;
for(int i=1;i<num_of_el;i++)
if(c[i]>c[index])
index=i;
return c[index];
}
Run Code Online (Sandbox Code Playgroud)
这是程序的主要部分:
int main(){
int a=7;
vector<decltype(a)> v;
v.push_back(a);
a=10;
v.push_back(5);
cout<<v[0]<<" "<<v[1]<<endl;
MaxElement(v,v.size())=10;
cout<<v[0]<<" "<<v[1]<<endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我在理解 MaxElement 函数如何工作方面没有问题,但在理解诸如->decltype(c[0])
? 那有什么作用?另外,我们怎样才能做类似的事情MaxElement(v,v.size())=10
,这里发生了什么?