相关疑难解决方法(0)

尾随返回类型语法样式应该成为新C++ 11程序的默认样式吗?

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++ auto c++11 trailing-return-type

80
推荐指数
4
解决办法
2万
查看次数

为什么在C++ 11中需要添加trailing-return-types?

我终于开始阅读,我不明白为什么需要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)没有工作,因为标识符lhsrhs仅解析阶段后有效.

我想我的问题是关于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在解析完整的函数体之后具有类型解析也可以正常工作?

c++ compilation c++11 trailing-return-type

13
推荐指数
1
解决办法
635
查看次数

function`-&gt;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,这里发生了什么?

c++ decltype trailing-return-type

0
推荐指数
1
解决办法
110
查看次数

标签 统计

c++ ×3

trailing-return-type ×3

c++11 ×2

auto ×1

compilation ×1

decltype ×1