jww*_*jww 2 c++ constexpr c++11
我试图装饰时遇到错误consexpr:
$ 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
}
^
Run Code Online (Sandbox Code Playgroud)
问题函数中使用的所有值都是模板参数.保存文件后,值不会更改.
难道不能将其表达为一种constexpr功能吗?
如果我做错了什么,那又是什么呢?如何修改ValidVaue成一个constexpr功能?
$ cat -n test.cxx
1 #include <string>
2 #include <iostream>
3
4 template <unsigned int min, unsigned int max, unsigned int step>
5 class MinMaxStep
6 {
7 public:
8 static constexpr unsigned int Min() { return min; }
9 static constexpr unsigned int Max() { return max; }
10 static constexpr unsigned int Step() { return step; }
11 static constexpr unsigned int ValidValue(unsigned int v)
12 {
13 if (v <= min) { return min; }
14 else if (v >= max) { return max; }
15 return (v+step-1) - ((v+step-1)%step);
16 }
17 };
18
19 int main (int argc, char* argv[])
20 {
21 MinMaxStep<10, 100, 10> mms;
22 unsigned int x = mms.ValidValue (18);
23 std::cout << "value " << x << std::endl;
24
25 return 0;
26 }
Run Code Online (Sandbox Code Playgroud)
constexprC++ 11中的函数规则非常严格.例如,可能只有一个return声明,没有别的.在C++ 14中,规则大大放松了.
有关详细信息,请参阅此constexpr参考.
有两种方法可以解决您的问题:最简单的方法是使用C++ 14(更改编译器标志使用-std=c++14).另一个解决方案是使用三元运算符将您的ValidValue函数重构为只有一个语句,一个return语句.
| 归档时间: |
|
| 查看次数: |
487 次 |
| 最近记录: |