C++ 为什么在使用constexpr时允许这样做?
我有下面的例子:C++ 为什么在使用constexpr时允许这样做?,c++,c++11,constexpr,C++,C++11,Constexpr,我有下面的例子: #include <iostream> using namespace std; constexpr int foo(int n){ return n; } int main(){ int n; cin >> n; int p[foo(n)]; cout << sizeof(p); // n * 4 return 0; } #包括 使用名称空间std; constexpr int foo(i
#include <iostream>
using namespace std;
constexpr int foo(int n){
return n;
}
int main(){
int n;
cin >> n;
int p[foo(n)];
cout << sizeof(p); // n * 4
return 0;
}
#包括
使用名称空间std;
constexpr int foo(int n){
返回n;
}
int main(){
int n;
cin>>n;
INTP[foo(n)];
cout这是一个编译器扩展,它允许非编译时大小的数组。您不需要foo
,因为它在可能的情况下会生成编译时值,但当您传递非编译时参数时,它当然也会在运行时起作用
有趣的是,现在甚至sizeof(p)
也不再是编译时值了:
#include <iostream>
using namespace std;
constexpr int foo(int n){
return n;
}
template<unsigned n> void f();
int main(){
int n;
cin >> n;
int p[foo(n)];
f<sizeof(p)>(); // oops
return 0;
}
#包括
使用名称空间std;
constexpr int foo(int n){
返回n;
}
模板void f();
int main(){
int n;
cin>>n;
INTP[foo(n)];
f();//噢
返回0;
}
收益率:
main.cpp:14:18: error: '(long unsigned int)((((sizetype)<anonymous>) + 1u) * 4u)' is not a constant expression
f<sizeof(p)>(); // oops
^
main.cpp:14:18:error:'(长无符号int)(((sizetype)这不是因为foo
是constepr
;直接传递n
也是有效的,因为编译器允许可变大小的数组()。我不记得这是否是C++11的官方功能。@Dave不,可变长度数组在C++11中是不允许的,它在C++14中的形式是有限的(与C相比)。我刚刚尝试了int p[n]并且工作正常!现在,我更困惑了…@Tracer您的编译器允许使用额外的功能(根据Joachim Pileborg的说法,这是非标准的,但很快就会出现)。简言之:您正在利用编译器的特殊功能。它不可移植。不要这样做:P@JoachimPileborg,运行时绑定的数组不在C++14中。它们已被删除。