In C , template arguments must be constant expressions. This means that their values must be known at compile time. The compiler cannot evaluate a non-constant variable in this context.
Consider the code:
template
void modify(){}
To pass a non-constant variable as the template argument, we might write:
for(int i = 0; i ();
}
However, this triggers an error because the compiler cannot determine the value of i at compile time. The loop body may execute multiple times, changing the value of i.
Instead of passing a non-constant variable directly, we can use template specialization to implement an iterative call:
#include
template
void modify() { std::cout "
void modify() { std::cout "
void modify() {
std::cout " ();
}
int main() {
modify();
}
To call modify with a value that is not known at compile time, we can use a technique called template metaprogramming. Here's a simplified example:
#include
template <:tuple>>
struct TupleSize;
template
struct TupleSize<:tuple>> {
static const int value = sizeof...(Args);
};
template
void callModify(int i) {
if constexpr (i ();
callModify(i 1);
}
}
int main() {
int n = 10;
callModify::value>(0);
}
In this example, callModify takes a parameter N which is the size of a tuple that contains the desired range of values for i. The function uses a recursive metaprogram to generate the calls to modify up to the specified size N.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3