C++ 最小/最大/步长函数和;constexpr函数体。。。“不是返回语句”;

C++ 最小/最大/步长函数和;constexpr函数体。。。“不是返回语句”;,c++,c++11,constexpr,C++,C++11,Constexpr,尝试用conexpr装饰时,我发现一个错误: $ g++ -std=c++11 test.cxx -o test.exe test.cxx: In instantiation of ‘static constexpr unsigned int MinMaxStep<min, max , step>::ValidValue(unsigned int) [with unsigned int min = 10u; unsigned int max = 100u; unsigned int

尝试用
conexpr
装饰时,我发现一个错误:

$ g++ -std=c++11 test.cxx -o test.exe
test.cxx: In instantiation of ‘static constexpr unsigned int MinMaxStep<min, max
, step>::ValidValue(unsigned int) [with unsigned int min = 10u; unsigned int max
 = 100u; unsigned int step = 10u]’:
test.cxx:22:40:   required from here
test.cxx:16:5: error: body of constexpr function ‘static constexpr unsigned int 
MinMaxStep<min, max, step>::ValidValue(unsigned int) [with unsigned int min = 10
u; unsigned int max = 100u; unsigned int step = 10u]’ not a return-statement
     }
     ^

在C++11中,
constexpr
函数的规则非常严格。例如,可能只有一个
return
语句,而没有其他语句。在C++14中,规则相当宽松

有关更多信息,请参见例如


解决问题有两种方法:最简单的方法是使用C++14(将编译器标志更改为使用
-std=C++14
)。另一种解决方案是使用三元运算符重构
ValidValue
函数,使其只有一条语句,即
return
语句。

return v=max?最大值:((v+step-1)-(v+step-1)%step))接受一个带有三元运算符的返回语句。你知道它是否被所有主要的编译器(Clang、Comeau、GCC、ICC、MSVC和SunCC)所接受吗?你知道他们有没有一个半生不熟的实现。。。C++14是不可能的。我们有时生活在一个特别的地狱里。我们在Fedora 1上支持GCC 3,在Windows 2000上支持Visual Studio.Net。@jww:但是
constexpr
仍然是您的选择吗?o_O@ildjarn-是的,
constxpr
,与其他关键字一样,如
noexcept
alignas
,可以抽象出来。我无法使旧编译器接受新标志:)