考虑以下C++代码:typedefstd::string&mutable_string_ref;conststd::stringstr="abc";mutable_string_refref(str);这显然会导致编译器错误,因为您无法创建对常量字符串的可变引用。对于GCC4.7.2,产生的错误是:error:invalidinitializationofreferenceoftype‘mutable_string_ref{akastd::basic_string&}’fromexpressionoftype‘conststring{akaconststd::basic_string}
考虑以下代码:templatevoidf(T){}templateconstexprintk(T&){return0;}intmain(){constexprautoi=1;f([&i]{f(0);});}clang++(trunk)编译它。g++(trunk)失败并出现以下错误::Inlambdafunction::11:19:error:nomatchingfunctionforcallto'f((*&i))>(int)'11|f(0);|^:1:35:note:candidate:'templatevoidf(T)'1|templatevoidf(T){}|^:1:35:note
这可能是一个有点不寻常的问题,因为它要求对anotherquestion的简短回答进行更全面的解释。以及与之相关的C++11标准的某些方面。为了便于引用,我将在这里总结所引用的问题。OP定义了一个类:structAccount{staticconstexprintperiod=30;voidfoo(constint&){}voidbar(){foo(period);}//noerror?};并且想知道为什么他在使用类内初始化静态数据成员时没有出错(一本书提到这是非法的)。JohannesSchaub的回答指出:这违反了一个定义规则;不需要诊断。尽管我非常依赖这个答案的来源和有效性,但老
回答后usingboostmathconstantsinconstexpr并建议OP对constexpr变量使用boost的模板化函数而不是非模板化常量来平息clang错误,我决定尝试看看什么条件会重现clang中的错误。让我们尝试复制boost的宏扩展到的内容:namespacedouble_constants{staticconstdoublename=25;}staticconstexprdoubleSEC3=double_constants::name;这会产生以下错误(按照Coliru进行)clang++-std=c++1y-O2-Wall-pedantic-pthreadm
我有一个类来描述一个类型的一些特征。templatestructmy_traits{staticconstexprintsome_trait=0;staticconstexprTmin(){returnstd::numeric_limtis::min();}staticconstexprTmax(){returnstd::numeric_limits::max();}};我想专攻my_traits::some_trait但是当我尝试时:templateconstexprintmy_traits::some_trait=1;编译器提示my_traits::some_trait已经有一个初
我得到的最小示例有点复杂:structA{};templatestructParent{};templateconstexprintoperator*(A,Parent*){returnN;}templateusingptr=T*;templatestructOther{};templatestructKid:Parent{staticOther{}>o;};intmain(){Kid{};}[gcc]编译代码没有任何问题,[clang]提示Parent与Kid匹配问题:prog.cc:7:15:note:candidatetemplateignored:couldnotmatch'P
当我定义一个constexpr函数时,我是否也应该将它声明为noexcept?我想在参数和用法满足编译时评估要求的情况下,潜在异常的含义是没有实际意义的。但对于在运行时评估函数的情况,它会照常适用。作为一个实际问题,如果函数确实简单,可能使用内置算术或转换,这样我希望编译器始终可以内联函数并对其进行优化,如果我离开noexcept对生成代码的效率有影响吗? 最佳答案 不,你不应该。“不能失败”和“可以在编译时求值”是正交问题。例如,你想写一个整数幂函数,但你想把幂作为有符号的(因为你认为无符号数应该只用于非常特殊的情况)。现在你说你
我做了一个constexpr字符串类型,我称之为StaticString。我从this得到这个想法网站。我遇到了一些奇怪的问题,编译器在一行中将变量视为constexpr,然后在下一行中不是constexpr。代码如下:constexprStaticStringhello="hello";constexprStaticStringhello2=hello+"";constexprStaticStringworld="world";constexprStaticStringboth=hello+"world";constexprStaticStringboth2=hello2+world
所以我需要log10功能来查找存储给定整数所需的字符数。但我想在编译时获取它,以根据我的代码中定义的这些整数常量静态确定char数组的长度。不幸的是log10不是constexpr函数,即使是整数版本也是如此。我可以像这样制作一个完整的版本:templateconstexprenable_if_t,size_t>intlen(Tparam){size_tresult{1U};while(T{}!=(param/=T{10}))++result;returnresult;}这最终将允许我这样做:constcharfoo[intlen(13)+1U]是否c++已经为此提供了一个工具,还是我
考虑以下C++11程序及其在GCC4.7.2中的结果:intmain(){constexprinti=0;int*p=i;}//g++-g-ggdb-Wall-Wextra-pedantic-std=c++11t.cpp//t.cpp:Infunction'intmain()'://t.cpp:4:13:error:invalidconversionfrom'int'to'int*'[-fpermissive]//t.cpp:4:9:warning:unusedvariable'p'[-Wunused-variable]根据标准:[C++11:4.10/1]:Anullpointerc