Skip to content

Instantly share code, notes, and snippets.

@xophiix
Last active August 29, 2015 14:19
Show Gist options
  • Save xophiix/b289f1ecb810198220ee to your computer and use it in GitHub Desktop.
Save xophiix/b289f1ecb810198220ee to your computer and use it in GitHub Desktop.
c++11 template
void printf(const char *s)
{
while (*s)
{
if (*s == '%' && *(++s) != '%')
throw std::runtime_error("invalid format string: missing arguments");
std::cout << *s++;
}
}
template<typename T, typename... Args>
void printf(const char* s, T value, Args... args)
{
while (*s)
{
if (*s == '%' && *(++s) != '%')
{
std::cout << value;
printf(*s ? ++s : s, args...); // 即便当*s == 0也会产生调用,以检测更多的类型参数。
return;
}
std::cout << *s++;
}
throw std::logic_error("extra arguments provided to printf");
}
template<typename... args>
struct Count{};
template<>
struct count<> {
static const int value = 0;
};
template<typename T, typename... Args>
struct count<T, Args...> {
static const int value = 1 + count<Args...>::value;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment