首先,我是一个菜鸟。我也是一个从未通过编写代码赚过一毛钱的看门人。这只是我喜欢做的事情。这是为了好玩:)话虽这么说,我写了这个基于控制台的井字游戏,它有足够的人工智能,不会输掉每场比赛。(我想ai应该叫它什么。)它有大约70个if/elseif语句用于计算机。我像这样使用了3个int数组:intL[2],M[2],R[2];0=空白;1=X;2=O;董事会然后“看起来”像L[0]|米[0]|R[0]L[1]|米[1]|R[1]L[2]|米[2]|R[2]所以我基本上写出了我能想到的每一种可能的情况:if(M[0]==1&M[1]==1&M[2]==0){M[2]=2;}//hereth
我环顾四周,但无法找到解决我的具体问题的方法。我有代码:templatetypenamestd::enable_if::value||std::is_enum::value,std::string>::typeconvertToString(constTargument){returnstd::to_string(argument);}std::stringconvertToString(std::stringstring);代码应该做什么:对任何数字类型(int、float、double和ENum)使用模板版本,对其他任何类型使用std::string版本。代码本身编译得很好,但是当
这个问题似乎与anexistingone有关,但我不明白theanswerthere中提供的“可移植解决方法”(涉及constautothis_=this;)而且我认为下面的例子更容易理解。我正在使用以下C++17代码片段(livedemo):#includestructTest{constchar*name_{nullptr};constTest*src_{nullptr};constexprTest(constchar*name)noexcept:name_{name}{}constexprTest(constTest&src)noexcept:src_{&src}{name_=s
我有一个std::vector并且我想检查一个特定的属性每个元素。SomeStruct有一个属性“类型”。我想检查这个属性为Type1或Type2。我的计划是使用boost::lambda。std::vector::const_iteratorit=std::find_if(vec.begin(),vec.end(),_1.type==SomeStruct::Type1||_1.type==SomeStruct::Type2);因为我需要访问每个元素的特定属性,所以我不确定我是否可以完全使用boost::lambda。有什么提示吗? 最佳答案
假设我想编写一个执行整数平方根的C++1y/14constexpr函数:constexprintconstexpr_isqrt(intx);我想执行完整性检查以确保x是非负数:constexprintconstexpr_isqrt(intx){if(x上面的???应该写什么?理想情况下,如果函数是在常量上下文中计算的,它应该会导致编译时错误,如果在运行时调用时会出现运行时错误(例如中止或抛出异常)。 最佳答案 你很幸运,有办法!即使在C++11中!使用异常(exception):#include#includeconstexprin
我想检查给定的double/浮点变量是否具有实际位模式0x0。不要问为什么,它用在Qt中的一个函数中(qIsNull()),我希望它是constexpr。原始代码使用了union:union{doubled;int64_ti;}u;u.d=d;returnu.i==0;这当然不能用作constexpr。下一次尝试使用reinterpret_cast:return*reinterpret_cast(&d)==0;但是虽然它在GCC4.7中作为constexpr工作,但它在Clang3.1中失败了(正确地,指针操作的b/c)。最后的想法是去Alexandrescuesque做这个:temp
我正在验证C++Primer上的声明:Unlinkeotherfunctions,inlineandconstexprfunctionsmaybedefinedmultipletimesintheprogram.我在下面使用了两个constexprcfunc()的定义,预计foo_0()将调用第一个def而foo_1()将调用2nddef。然而,尝试因编译错误而失败(最后)。为什么?constexprintcfunc(){return42;}intfoo_0(){returncfunc();}constexprintcfunc(){return42;}intfoo_1(){return
考虑以下代码:staticconstexprintmake_const(constinti){returni;}voidt1(constinti){constexprintii=make_const(i);//erroroccurshere(iisnotaconstantexpression)std::cout为什么我在调用make_const时出错?更新但是这个有效:constexprintt1(constinti){returnmake_const(i);}然而,这不是:templateconstexprbooldo_something(){returni;}constexprin
考虑一个在运行时只包装一个值的类:templateclassNonConstValue{public:NonConstValue(constType&val):_value(val){;}Typeget()const{return_value;}voidset(constType&val)const{_value=val;}protected:Type_value;};以及它的constexpr版本:templateclassConstValue{public:constexprConstValue(constType&val):_value(val){;}constexprTypeg
我有一个看起来像这样的constexpr函数:constexprintfoo(intbar){static_assert(bar>arbitrary_number,"Usealowernumberplease");returnsomething_const;}但是,用GCC4.6.3编译这个一直告诉我错误:'bar'不能出现在常量表达式中我试过类似的东西constexprintfoo(constexprconstintbar){static_assert(bar>arbitrary_number,"Usealowernumberplease");returnsomething_cons