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:
<code class="cpp">template <int a> void modify(){}</code>
To pass a non-constant variable as the template argument, we might write:
<code class="cpp">for(int i = 0; i < 10; i++) { modify<i>(); }</code>
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:
<code class="cpp">#include <iostream> template<> void modify<0>() { std::cout << "modify<0>" << std::endl; } template<> void modify<1>() { std::cout << "modify<1>" << std::endl; } // ... template<int i> void modify() { std::cout << "modify<" << i << ">" << std::endl; modify<i+1>(); } int main() { modify<0>(); }</code>
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:
<code class="cpp">#include <tuple> template <std::tuple<int...>> struct TupleSize; template <int... Args> struct TupleSize<std::tuple<Args...>> { static const int value = sizeof...(Args); }; template <int N> void callModify(int i) { if constexpr (i < N) { modify<i>(); callModify<N>(i+1); } } int main() { int n = 10; callModify<TupleSize<std::make_tuple(1,2,3,4,5,6,7,8,9,10)>::value>(0); }</code>
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.
The above is the detailed content of Why Can\'t Non-Constant Variables Be Used as Template Arguments in C ?. For more information, please follow other related articles on the PHP Chinese website!