通过作为常量传递给函数来设置结构中数组的大小 - 非类型模板参数不是常量表达式
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
。对于其余代码,此数字将为 constant
。我想创建一个函数来传递和创建一个结构,其中包含一个大小为 k 的数组和该数字。但是,编译returns这个错误:
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++ 的编译时特性。
模板仅在编译时处理。您不能将 运行 时间变量(如函数参数)传递给模板。对于您要执行的操作,您将不得不使用 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;
}
关于模板的基本原则是:
Any template argument must be a quantity or value that can be determined at compile time.
这在模板实体的运行时成本方面具有显着优势。
但在您的示例中,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;
}
程序输出可见here.
用户在 运行 时设置 k
。对于其余代码,此数字将为 constant
。我想创建一个函数来传递和创建一个结构,其中包含一个大小为 k 的数组和该数字。但是,编译returns这个错误:
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++ 的编译时特性。
模板仅在编译时处理。您不能将 运行 时间变量(如函数参数)传递给模板。对于您要执行的操作,您将不得不使用 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;
}
关于模板的基本原则是:
Any template argument must be a quantity or value that can be determined at compile time.
这在模板实体的运行时成本方面具有显着优势。
但在您的示例中,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;
}
程序输出可见here.