Home > Backend Development > C++ > Why can\'t I use a non-constant variable as a template argument in C ?

Why can\'t I use a non-constant variable as a template argument in C ?

Susan Sarandon
Release: 2024-10-29 08:53:30
Original
701 people have browsed it

 Why can't I use a non-constant variable as a template argument in C  ?

Non-Constant Template Argument Conundrum

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template