出于学习目的,我重新实现了boost::hana::is_valid。用例是:structPerson{std::stringname;};intmain(){autohas_name=is_valid([](auto&&t)->decltype((void)t.name){});Personjon{"snow"};static_assert(has_name(jon),"");static_assert(!has_name(1),"");}实现:namespacedetail{templatestructis_valid_impl{template>constexprbooloper
在C++11中,这两行是等价的。据我所知,advantageofthesecondsyntax是返回类型在类范围内。因此,您可以直接使用类的嵌套类型和非静态成员的decltype表达式。此外,函数名称排列得很好。intfoo(intbar);autofoo(intbar)->int;这里使用了auto关键字,也可以用来自动导出局部变量的类型。但是,我在这里看不到类比。在函数声明语法中,没有派生任何东西。箭头后面明确提到了返回类型。就我个人而言,我会说没有auto关键字语法会更清晰。这背后有什么用意吗?哪个? 最佳答案 论文"Decl
当返回类型是类时,GCC4.9.1似乎不喜欢带有尾随返回类型和属性的函数声明。考虑以下简单的测试用例:structbar{inta;bar(inta):a(a){}};autofoo()->bar__attribute__((unused));autofoo()->bar{returnbar(5);}intmain(){return0;}GCC打印关于属性的奇怪警告:argh.cpp:2:41:warning:ignoringattributesappliedtoclasstype‘bar’outsideofdefinition[-Wattributes]autofoo()->bar_
我正在尝试覆盖虚拟,但也使用关键字override、final和const,以及尾随返回类型。问题似乎出在派生类中,编译器错误(说我没有指定尾随返回类型)并没有太大帮助。代码在这里:https://wandbox.org/permlink/zh3hD4Ukgrg6txyE也贴在下面。我玩过不同的顺序,但似乎仍然无法正确处理。任何帮助将不胜感激,谢谢。#includeusingstd::cout;usingstd::endl;usingstd::ostream;////////////////////////////////////////////////BasestuffclassBa
我经常看到这种形式的例子:templateautoadd(T&&t,U&&u)->decltype(std::forward(t)+std::forward(u)){returnstd::forward(t)+std::forward(u);}但我敢说这是更好更正确的方法:templateautoadd(T&&t,U&&u)->decltype(t+u)//noforwardinghere{returnstd::forward(t)+std::forward(u);}为什么?首先,此示例中的decltype仅需推导返回类型,因此(t+u)不是(std::forward(t)+std::
关于之前的问题(IsitpossibletoreturnanobjectoftypeTbyreferencefromalambdawithoutusingtrailingreturntypesyntax?),我想知道是否还有任何其他重要的案例或示例,其中trailing-return-type语法在使用lambda时可以不被避免。 最佳答案 在C++14中,一个有点人为的例子是将sfinae与通用lambda结合使用:[](auto&&arg)->decltype(arg.f(),void()){/*dowhateveryouwan
我发现尾随返回类型很容易定义返回复杂类型的函数的返回值,例如:autoget_diag(int(&ar)[3][3])->int(&)[3]{//usingtrailingreturntypestaticintdiag[3]{ar[0][0],ar[1][1],ar[2][2]};returndiag;}auto&get_diag2(int(&ar)[3][3]){//adding&autobecauseotherwiseitconvertsthearraytopointerstaticintdiag[3]{ar[0][0],ar[1][1],ar[2][2]};returndiag;
auto可以推导出返回类型那么为什么我们需要尾部箭头符号(->)来推导出返回类型#includeautoadd(inti,intj)->int{returni+j;}intmain(){intx=10,y=20;std::cout 最佳答案 在C++11中,函数没有返回类型推导。auto不是这里推导的占位符类型。你可以说它的意义重载了。对于函数,auto只是意味着返回类型将被指定为尾随返回类型。你不能省略尾随返回,否则你的程序将是错误的。此功能已添加到语言中,以允许返回类型规范取决于函数参数或成员的封闭类。在达到尾随返回类型时,这些
关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭5年前。ImprovethisquestionC++11支持新的函数语法:autofunc_name(intx,inty)->int;目前这个函数将被声明为:intfunc_name(intx,inty);新风格似乎还没有被广泛采用(比如在gccSTL中)但是,这种新风格应该在新的C++11程序中随处可见,还是只在需要时才使用?就我个人而言,如果可能的话,我更喜欢旧的风格,但是混合风格的代码库看起来很难看。
我正在尝试使用decltype理解C++11中基于尾随返回的新函数声明语法。在下面的代码中,我尝试定义一个返回const&的成员函数,以允许对i进行只读访问#include#includestructX{int&i;X(int&ii):i(ii){}//autoacc()const->std::add_const::type{returni;}//failstheconstnesstestautoacc()const->decltype(i){returni;}//failstheconstnesstest//constint&acc()const{returni;}//worksas