[英]Setting the size of array in a struct by passing as a const to a function - Non-type template argument is not a constant expression
用户在运行时设置k
。 对于代码的 rest,此数字将保持constant
。 我想创建一个 function 来传递并创建一个结构,该结构包含一个大小为 k 的数组,该数组具有该数字。 但是,编译器返回此错误:
Non-type template argument is not a constant expression
任何建议将不胜感激。
代码如下:
template <int N>
struct UL {
unsigned long ul [N];
};
void func(const int k){
UL<k> x; //problem is here
}
int main () {
int k;
cin >> k;
func(k);
return 0;
}
变量k
是在运行时设置的,所以在编译代码时,编译器不知道k
的值是什么。 你不能这样做。 但是,如果您知道您的k
值将是什么并且它的值范围是有限的,您可以为每个可能的k
值创建您的结构,并在运行时选择匹配的 class。 当然,这可能不是您想要的。 您只需要能够区分编译时和运行时已知的内容。 模板文字(我希望我使用了正确的名称)是 C++ 的编译时特性。
模板仅在编译时处理。 您不能将运行时变量(例如 function 参数)传递给模板。 对于您要执行的操作,您必须改用std::vector
,例如:
#include <vector>
struct UL {
std::vector<unsigned long> ul;
};
void func(const int k){
UL x;
x.ul.resize(k);
}
int main () {
int k;
cin >> k;
func(k);
return 0;
}
关于模板的一个基本原则是:
任何模板参数都必须是可以在编译时确定的数量或值。
这对模板实体的运行时成本具有显着优势。
但是在您的示例中, k
不是编译时间常数,并且您将其用作模板参数,因此由于上述引用的语句,您会收到错误。
要解决您的问题,您可以使用std::vector
,如下所示:
#include <iostream>
#include <vector>
struct UL {
std::vector<unsigned long> ul;
//constructor
UL(int k): ul(k) //this creates vector ul of size k
{
std::cout<<"size of vector set to: "<<ul.size()<<std::endl;
}
};
void func(const int k){
UL x(k); //pass k as argument to constructor
}
int main () {
int k;
std::cin >> k;
func(k);
return 0;
}
程序的output可以看这里。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.