Last active
August 29, 2015 14:19
-
-
Save xophiix/b289f1ecb810198220ee to your computer and use it in GitHub Desktop.
c++11 template
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
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"); | |
} |
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
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