samedi 25 juin 2022

static variable in variadic template function [duplicate]

I want to use a static variable in a function which accept variadic template to accept variable number of arguments. Since the function gets called recursively I expect the value of i to be incremented for each call. But the static variable is incremented only once rather than for each function call. Here is the program which demonstrate this behavior.

#include <iostream>
#include <string>

using namespace std::string_literals;

void printArgs() {}

template<typename T, typename... Ts>
void printArgs(T first, Ts... rest)
{
    static int32_t i{};
    ++i;
    std::cout << i << ". " << first << std::endl;
    printArgs(rest...);
}

int main()
{
    printArgs("hello cpp"s, "c++11", 'x', 1234, 0xab45, 0b010101);
}

Output

1. hello cpp
1. c++11
1. x
1. 1234
1. 43845
1. 21

If I make the static variable global by moving it outside the function definition, it gets incremented for each function invocation.

static int32_t i{};
template<typename T, typename... Ts>
void printArgs(T first, Ts... rest)
{
    ++i;
    std::cout << i << ". " << first << std::endl;
    printArgs(rest...);
}

output

1. hello cpp
2. c++11
3. x
4. 1234
5. 43845
6. 21

How the variadic templates function behave in this scenario? Does the compiler create a separate function for each function invocation?

Aucun commentaire:

Enregistrer un commentaire