Skip to content

Instantly share code, notes, and snippets.

@safiire
Created May 16, 2016 07:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save safiire/92606e854f76c224b6ebc8b83eaf4585 to your computer and use it in GitHub Desktop.
Save safiire/92606e854f76c224b6ebc8b83eaf4585 to your computer and use it in GitHub Desktop.
Interesting way of using the new variadic templates to create a variadic print() function.
// Compile with: g++ -std=c++11 variadic_print.cpp -o variadic_print
#include <iostream>
// No argument case
void print() {}
// Recursive Variadic Template
template <typename HEAD, typename ... TAIL>
void print(const HEAD& head, const TAIL& ... tail) {
std::cout << head << std::endl;
print(tail...);
}
int main(){
print(1, 2, 3, 3.14159, "Slick use of templates");
return 0;
}
@safiire
Copy link
Author

safiire commented Jul 31, 2017

Fun, but for each call with n arguments it actually generates n separate but nearly identical templated print<> functions, even at -O3.

ie

0x100000670    1 166          sym.voidprint_int_int_int_double_char_23___intconst__intconst__intconst__doubleconst__charconst____23__
0x100000730    1 155          sym.voidprint_int_int_double_char_23___intconst__intconst__doubleconst__charconst____23__
0x1000007e0    1 148          sym.voidprint_int_double_char_23___intconst__doubleconst__charconst____23__
0x100000890    1 137          sym.voidprint_double_char_23___doubleconst__charconst____23__
0x100000930    1 135          sym.voidprint_char_23___charconst____23__

Not practical, but I still thought it was cute.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment