我一直在使用解析为与声明相同类型的定义中的推导返回类型。这有效:templatestructCls{staticstd::size_tf();};templatedecltype(sizeof(int))Cls::f(){return0;}但是,如果我通过替换sizeof(int)将定义更改为应该等效的内容与sizeof(T)itfailstemplatedecltype(sizeof(T))Cls::f(){return0;}gcc的错误(clang几乎相同):error:prototypefor‘decltype(sizeof(T))Cls::f()’doesnotmatchany
我想自动推断我正在编写的函数的返回类型。例子:std::vectortest(){decltype(this_function)ret;ret.push_back(5);ret.push_back(9);returnret;}到目前为止,我取得的最好成绩是std::vectortest(){decltype(test())ret;ret.push_back(5);ret.push_back(9);returnret;}哪个有效但是:如果我更改函数名称,我必须更改decltype(test())进入decltype(name())如果我更改函数参数,我也必须更改decltype(test
给定structA{intfoo(doublea,std::string&b)const;};我可以像这样创建一个成员函数指针:typedefint(A::*PFN_FOO)(double,std::string&)const;很简单,只是如果A::foo的签名发生变化,则需要更新PFN_FOO。由于C++11引入了decltype,是否可以用来自动推导出签名并创建typedef? 最佳答案 是的,当然:typedefdecltype(&A::foo)PFN_FOO;您也可以通过using定义类型别名关键字(感谢MatthieuM.
对于以下代码:autoF(intcount)->decltype([](intm){return0;}){return[](intm){return0;};}g++4.5给出错误:test1.cpp:1:32:error:expectedprimary-expressionbefore'int'test1.cpp:1:32:error:expected')'before'int'有什么问题?从函数返回lambda的正确方法是什么? 最佳答案 您不能使用lambda表达式,除非通过实际创建该对象-这使得无法像decltype这样传递类
我正在阅读thisarticleonWikipediaregardingC++11TypeInferencefeature.有一个例子,我引用:#includeintmain(){conststd::vectorv(1);autoa=v[0];//ahastypeintdecltype(v[1])b=1;//bhastypeconstint&,thereturntypeof//std::vector::operator[](size_type)constautoc=0;//chastypeintautod=c;//dhastypeintdecltype(c)e;//ehastypein
考虑以下程序:intmain(){constinte=10;for(decltype(e)i{0};i使用clang(以及gcc)编译失败:decltype.cpp:5:35:error:read-onlyvariableisnotassignablefor(decltype(e)i{0};i基本上,编译器假设i必须是const,因为e是。有没有办法我可以使用decltype来获取e的类型,但删除const说明符? 最佳答案 为此,我更喜欢autoi=decltype(e){0};。它比使用type_traits简单一些,而且我觉得
Edit,inordertoavoidconfusion:decltypedoesnotaccepttwoarguments.Seeanswers.以下两个结构可用于在编译时检查类型T上的成员函数是否存在://Non-templatedhelperstruct:struct_test_has_foo{templatestaticautotest(T*p)->decltype(p->foo(),std::true_type());templatestaticautotest(...)->std::false_type;};//Templatedactualstruct:templates
我很少看到decltype(auto),但是当我看到它时,我会感到困惑,因为它似乎在从函数返回时与auto做同样的事情。autog(){returnexpr;}decltype(auto)g(){returnexpr;}这两种语法有什么区别? 最佳答案 auto遵循模板参数推导规则,始终为对象类型;decltype(auto)遵循decltype规则,根据值类别推导引用类型。所以如果我们有intx;int&&f();然后expressionautodecltype(auto)-----------------------------
据我了解,decltype和auto都会尝试找出某物的类型。如果我们定义:intfoo(){return34;}那么这两个声明都是合法的:autox=foo();cout你能告诉我decltype和auto的主要区别是什么吗? 最佳答案 decltype给出传递给它的表达式的声明类型。auto和模板类型推导一样。因此,例如,如果您有一个返回引用的函数,auto仍然是一个值(您需要auto&来获取引用),但decltype就是返回值的类型。#includeintglobal{};int&foo(){returnglobal;}intm
(如果您是C++11专业人士,请跳至粗体段落。)假设我想编写一个模板方法,该方法调用并返回传递的对象的结果,该对象的类型是模板参数:templateReturnTypedoSomething(constT&foo){returnfoo.bar();//EDIT:Mightalsobeanexpressionintroducingatempval}所以T必须有方法ReturnTypeT::bar()const为了在这样的调用中使用:structMyClass{...intbar()const;...};...MyClassobject;intx=doSomething(object);我