In C , template arguments are restricted to constant expressions because the compiler needs to determine their values during compilation. Constant expressions are those that can be evaluated solely based on information available at compile time, excluding variables and function calls.
In the provided code:
<code class="cpp">for(int i = 0; i < 10; i++) { modify<i>(); }</code>
The template argument i is not a constant expression because its value depends on the loop counter variable, which is evaluated during runtime. Therefore, the compiler cannot determine i's value at compile time and raises an error.
To achieve your goal without modifying the library interface, you can use a technique called template metaprogramming. Here's an approach:
<code class="cpp">template<int I = 1> void modify_loop() { modify<I>(); modify_loop<I + 1>(); } // Call the recursive function with the starting value modify_loop<>();</code>
This approach starts with a template function modify_loop that has a default value I set to 1. Inside the function, it calls modify with the current I value and then recursively calls itself with I incremented. The recursion continues until I reaches the desired value of 10.
To call modify where VAR is the output of a functional computation, you can use a technique called expression templates. Here's an example:
<code class="cpp">struct Func { template<typename T> T operator()(T arg) { return arg + 10; } }; constexpr auto VAR = Func()(); // Evaluate the function and store the result template<typename Value> void modify(Value arg) { ... } // Call modify with VAR as the argument modify(VAR);</code>
In this example, the Func struct defines a function object that adds 10 to its argument. The VAR variable stores the output of this function, and the modify function accepts a template argument of any type. By instantiating modify with VAR, you effectively pass the result of the function as an argument.
The above is the detailed content of Why Can\'t I Use a Loop Variable as a Template Argument in C ?. For more information, please follow other related articles on the PHP Chinese website!