Last active
December 22, 2016 14:35
-
-
Save mkmkme/a81bfe7bcf05e002364925cb66893a33 to your computer and use it in GitHub Desktop.
some tricks with variadic templates
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// g++ -Wall -std=c++14 | |
#include <iostream> | |
template <typename... Ts> | |
size_t get_sum(const Ts&... args) | |
{ | |
size_t s = 0; | |
for (const auto& a : {args...}) | |
s += a; | |
return s; | |
} | |
template <typename... Ts> | |
void print_all(const Ts&... args) | |
{ | |
for (const auto& a : {args...}) | |
std::cout << a << " "; | |
std::cout << std::endl; | |
} | |
int main() | |
{ | |
std::cout << get_sum(1, 2, 3) << std::endl; | |
print_all("foo", 1, "bar", "baz"); // an error will be here | |
return 0; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
template <class H> void print(H h) | |
{ | |
std::cout << h << std::endl; | |
} | |
template <class H, class... T> void print(H h, T... t) | |
{ | |
std::cout << h << " "; | |
print(t...); | |
} | |
int main() | |
{ | |
print("foo", "bar", 42, "baz"); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment