可变参数模板在c ++ 11中引入.我发现可以使用它替换printf函数.但是,cout用于实现.我想知道是否有可能使用其他东西来实现类型安全但不牺牲太多性能.
void safe_printf(const char *s)
{
while (*s) {
if (*s == '%') {
if (*(s + 1) == '%') {
++s;
}
else {
throw "invalid format string: missing arguments";
}
}
std::cout << *s++;
}
}
template<typename T, typename... Args>
void safe_printf(const char *s, T& value, Args... args)
{
while (*s) {
if (*s == '%') {
if (*(s + 1) == '%') {
++s;
}
else {
std::cout << value;
safe_printf(s + 1, args...); // …Run Code Online (Sandbox Code Playgroud)