Jon*_*Mee 2 c++ compile-time-constant constexpr c++11 visual-studio-2017
我有以下代码:
constexpr int log2(const unsigned int x) {
return x < 4 ? 1 : 1 + log2(x / 2);
}
int main() {
bitset<log2(2)> foo;
int bar[log2(8)];
cout << log2(8) << endl;
}
Run Code Online (Sandbox Code Playgroud)
这在gcc中可以正常工作:https://ideone.com/KooxoS
但是当我尝试使用visual-studio-2017时,出现以下错误:
错误C2975::预期的编译时常量表达式的
_Bits无效模板参数 注:请参见 错误C2131的声明:表达式未求值为常量 注:失败是由未定义函数的调用或未声明的 注引起的:请参见std::bitset_Bitsconstexprlog2
显然log2是constexpr这样,所以我认为这只是visual-studio-2017中的错误。有办法解决这个错误吗?
看起来您的项目包含std::log2编译器与您的log2函数混淆的标准函数。即使您不这样做,也会发生这种情况,#include <cmath>因为标准标头被允许包含任何其他标准标头。这也是using namespace std;回火的另一个例子。
一种解决方案是将您的constexpr函数重命名为其他名称:
#include <bitset>
#include <iostream>
using namespace std;
constexpr int logTwo(const unsigned int x) {
return x < 4 ? 1 : 1 + logTwo(x / 2);
}
int main() {
bitset<logTwo(2)> foo;
int bar[logTwo(8)];
cout << logTwo(8) << endl;
}
Run Code Online (Sandbox Code Playgroud)
编辑:似乎using namespace std;在这种情况下可能无关。log2无论如何,标准函数可能在全局名称空间中可用。
| 归档时间: |
|
| 查看次数: |
134 次 |
| 最近记录: |