I came across variadic templates while reading a book and thought it would be pretty cool to implement a python style print
function.
Here is the code.
#include <iostream>
#include <string>
#define None " "
template<typename T, typename... Tail>
void print(T head, Tail... tail, const char* end = "\n")
{
std::cout << head << end;
if constexpr (sizeof...(tail) > 0)
{
print(tail..., end);
}
}
int main()
{
// Error: no instance of function template "print" matches the argument list
print("apple", 0, 0.0f, 'c', true);
// Error: no instance of function template "print" matches the argument list
print("apple", 0, 0.0f, 'c', true, None);
}
Expected result from those two function calls:
First: Second:
apple apple 0 0.0f 'c' 1
0
0.0f
'c'
1
Removing const char* end = "\n"
from the function signature gets the code to compile, but I want that functionality of specifying the last parameter to state whether to print a newline.
Is this possible at all?