Skip to content

Instantly share code, notes, and snippets.

@mkmkme
Last active December 22, 2016 14:35
Show Gist options
  • Save mkmkme/a81bfe7bcf05e002364925cb66893a33 to your computer and use it in GitHub Desktop.
Save mkmkme/a81bfe7bcf05e002364925cb66893a33 to your computer and use it in GitHub Desktop.
some tricks with variadic templates
// 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;
}
#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