Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Recursive variadic function template call

I have these two implementations for a function:

First implementation

void print() {}

template<typename T, typename... Ts>
void print(T first, Ts... args) {
    std::cout << first << '\n';
    print(args...);
}

Second implementation

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

template<typename T>
void print(T t) {
    std::cout << t << '\n';
}

template<typename T, typename... Ts>
void print(T first, Ts... args) {
    print(first);
    print(args...);
}

I would like to ask why in the second implementation the last call to the print function
when the args... expansion will evaluate to an empty argument list is OK. Outside of the definition of the print function there is not possible to call print() with no arguments.

I will attach a simple main function to make it easy for someone to play with the code.

int main() {
    using namespace std::literals::string_literals;

    print("hello"s, 22, "world"s);
}

>Solution :

why in the second implementation the last call to the print function when the args… expansion will evaluate to an empty argument list is OK

Because the second implementation is never called with a single argument. Instead the non-variadic version is used for a single argument template<typename T> void print(T t).

Basically, args... will never expand to an empty argument list. because the non-variadic version is available which will be preferred over the variadic version for a single function argument call as print("world"s).

You can also verify this at cppinsights

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading