Home >Backend Development >C++ >Why can\'t I use a non-constant variable as a template argument in C ?
When attempting to pass a non-constant variable as a template argument, such as i in the following code snippet, the compiler issues an error:
<code class="cpp">template <int a> void modify() {} for (int i = 0; i < 10; i++) { modify<i>(); // error: 'i' cannot appear in constant-expression }</code>
Reason for the Error:
Templates are expanded during compilation, which requires their arguments to be evaluated at compile time. Since i is modified within the loop, the compiler cannot determine its value at compile time, leading to the error.
Alternative Implementation:
To achieve the desired iteration without altering the API interface, consider implementing the following:
<code class="cpp">#include <iostream> template<int i> void modify() { std::cout << "modify<" << i << ">" << std::endl; } template<int x, int to> struct static_for { void operator()() { modify<x>(); static_for<x+1,to>()(); } }; template<int to> struct static_for<to,to> { void operator()() {} }; int main() { static_for<0,10>()(); }</code>
This version utilizes recursion to emulate iteration. By instantiating specialized template functions for each value (e.g., modify<0>, modify<1>, etc.), the code simulates the loop behavior from i=0 to i=9.
Non-Constant Template Argument Resolution:
To call modify with a variable argument VAR (determined by a functional computation), consider using a template function with variadic parameters, as follows:
<code class="cpp">template <typename T> void modify(const T& x) { std::cout << "modify(" << x << ")" << std::endl; } int main() { auto VAR = ...; // computed from some functional process modify(VAR); }</code>
The above is the detailed content of Why can\'t I use a non-constant variable as a template argument in C ?. For more information, please follow other related articles on the PHP Chinese website!