Visual studio 2017 在Visual Studio中处理忽略的constexpr?

Visual studio 2017 在Visual Studio中处理忽略的constexpr?,visual-studio-2017,c++,c++11,constexpr,compile-time-constant,Visual Studio 2017,C++,C++11,Constexpr,Compile Time Constant,我有以下代码: 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; } constexpr int log2(const unsigned int x){

我有以下代码:

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;
}
constexpr int log2(const unsigned int x){
返回x<4?1:1+log2(x/2);
}
int main(){
比特集foo;
内部条形图[log2(8)];
库特
显然
log2
constexpr

函数为
constexpr
并不意味着它总是可以用来计算计算时间值。当
x>=4
时,您正在调用,而不是
constexpr
本身


GCC将它们实现为一个扩展。请参阅。看起来您的项目包含标准的
std::log2
函数,编译器会将其和
log2
函数混淆。即使您不包含
,也可能发生这种情况,因为标准头可以包含任何其他标准头这也是
使用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;
}
#包括
#包括
使用名称空间std;
constexpr int logTwo(const unsigned int x){
返回x<4?1:1+logTwo(x/2);
}
int main(){
比特集foo;
内部条形图[logTwo(8)];

cout看起来像是visual studio的问题。请尝试visual studio 2019,因为它们在标准遵从性方面往往稍显落后。如果我将其重命名为log22(或Log2)它在VS2017中编译,我得到的只是
警告C4101:'bar':未引用的局部变量
,输出打印3。它似乎拾取了一个不是constexpr?@NathanOliver的标准库。这是一个糟糕的重复。我可以在本地获得相同的编译错误,而不必使用命名空间std;
@FrançoisAndrieux,因为。请参阅also@Borgeader评论不错。这就是问题所在,谢谢。我很快会接受其中一个答案。我还要补充一点,名称冲突是因为使用了namespace@GuillaumeRacicot@MaxLanghof噢,是的,我忘了数学函数也可能位于全局名称空间中