User sets k
at running time. This number will be constant
for the rest of the code. I want to create a function to pass and create a struct that includes an array of size k with that number. However, the compiler returns this error:
Non-type template argument is not a constant expression
Any recommendation will be appreciated.
The code is like:
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;
}
Variable k
is set at runtime, so when the code is being compiled, the compiler doesn't know what the value of k
is. You can't do this. But if you know what your k
value is going to be and the range of values it can be is limited, you can create your struct for each possible value of k
and choose the matching class at runtime. Of course this is not probably what you want. You just need to be able to distinguish between what is known at compile-time and at runtime. Templated literals (I hope I used the right name) are a compile-time feature of C++.
Templates are processed at compile-time only. You can't pass a run-time variable, like a function parameter, to a template. For what you are trying to do, you will have to use std::vector
instead, eg:
#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;
}
A fundamental principle about templates is that:
Any template argument must be a quantity or value that can be determined at compile time .
This has dramatic advantages on the runtime cost of template entities.
But in your example, k
is not a compile time constant and you're using it as a template argument and so as a consequence of the above quoted statement you get the error.
To solve your problem you can use a std::vector
as shown below:
#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;
}
The output of the program can be seen here .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.