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
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