这是一个简化的代码示例,旨在生成任意值序列(在std::iota的意义上)和在它们之上的不同类别的迭代器:structdelta{templatevoidinc(I&i){++i;}templateInext(Ii){inc(i);returni;}};delta类有很多,每个类定义inc的方式不同,例如--i,i+=step,i-=step,i*=step,f(i)等函数next保持不变,实际上在基类中共享。我们正在从inc的变异操作中生成next的基于值的操作。做相反的事情是等价的,但是我们选择这种设计是为了性能,因为next只期望在某些初始化时被调用,而inc可能被调用一百万次。
我不确定这是编译器错误还是我误解了constexpr:structS{};constexprSs1{};constexprSs2;structtest{staticconstexprautot1=s1;staticconstexprautot2=s2;//errorhere};GCC4.8给我一个奇怪的错误“错误:字段初始值设定项不是常量”。s2真的不是常数吗?如果是,为什么?为了清楚起见,我实际上在我的代码中使用了一堆空结构(用于元编程https://github.com/porkybrain/Kvasir)所以我真的对这个特定示例很感兴趣。 最佳答案
N45277.1.5[dcl.constexpr]p9Aconstexprspecifierusedinanobjectdeclarationdeclarestheobjectasconst.Suchanobjectshallhaveliteraltypeandshallbeinitialized.Ifitisinitializedbyaconstructorcall,thatcallshallbeaconstantexpression(5.20).Otherwise,orifaconstexprspecifierisusedinareferencedeclaration,everyf
我正在使用一个简单的SFINAE技巧来检查成员函数是否存在,如下所示:#includetemplatestructhas_size{templatestaticconstexprautocheck(T*)->decltype(std::declval().size(),std::true_type{});templatestaticconstexprautocheck(...)->std::false_type;staticconstexprboolvalue=decltype(check(nullptr))::value;};//Usage:static_assert(has_siz
我喜欢在我的一个ctors以编译时已知值被调用时做一些检查。有办法检测吗?所以当有人调用它时:Aa(10);因为10是编译时已知常量,所以我喜欢调用一个特殊的构造函数,如下所示:template>A(intValue){}知道如何解决这个问题吗?谢谢! 最佳答案 积分常量可以解决您的问题:structA{template*=nullptr>A(std::integral_constant){}};然后,你可以像这样使用它:Aa{std:integral_constant{}};为了便于使用,您还可以使用类似于boost::hana的
constexpr移动构造函数是否有意义?例如,考虑以下内容:#includeclassC{public:constexprC(std::arrayar):m_ar{ar}{}constexprC(C&&other):m_ar{std::move(other.m_ar)}{}private:std::arraym_ar;};intmain(){constexprCc1{{{1,2,3}}};constexprCc2{std::move(c1)};return0;}这不会编译,因为尽管在c1上调用了std::move,编译器推断它需要使用(隐式删除的)复制构造函数,而不是移动构造函数。我
根据cppreference(强调我的):Acoreconstantexpressionisanyexpressionthatdoesnothaveanyoneofthefollowinginanysubexpression(...)Anexpressionwhoseevaluationleadstoanyformofcorelanguageundefinedbehavior(includingsignedintegeroverflow,divisionbyzero,pointerarithmeticoutsidearraybounds,etc).Whetherstandardlibr
考虑这段代码:structT{boolstatus;UsefulDatadata;};std::forward_listlst;lst.remove_if([](T&x)->bool{returnx.status=!x.status;});即一次性切换状态和删除非事件元素。根据cppreference上面的代码似乎是未定义的行为(强调我的):templatevoidremove_if(UnaryPredicatep);p-unarypredicatewhichreturnstrueiftheelementshouldberemoved.Thesignatureofthepredicat
考虑一个简单的效用函数来计算合取,并使用这个效用来确保std::tuple中的类型都相等。#include#includeconstexprautoall()noexcept->bool{returntrue;}templateconstexprautoall(boolconstx,Bools...xs)noexcept->bool{returnx&&all(xs...);}templatestructfoo;templatestructfoo,std::enable_if_t::value...)>>{};intmain(){foo>x;}GCC和Clang可以处理这段代码,但MSV
GCC8.2.1和MSVC19.20编译以下代码,但Clang8.0.0和ICC19.0.1无法编译。//Baseclass.structBase{};//Dataclass.structData{intfoo;};//Derivedclass.structDerived:Base,Data{intbar;};//Mainfunction.intmain(){constexprintData::*data_p{&Data::foo};constexprintDerived::*derived_p{data_p};constexprintBase::*base_p{static_cast