2014-10-06 2 views
0

Я получил некоторый пример кода, чтобы сделать C++ VARIADIC шаблон здесь:C++ 11 VARIADIC Шаблон

http://en.wikipedia.org/wiki/Variadic_template

Мой код выглядит следующим образом.

#ifdef DEBUG 
    #define logDebug(x, ...) streamPrintf(x, ##__VA_ARGS__); 
#else 
    #define logDebug(x, ...) 
#endif 

void streamPrintf(const char *s); 
template<typename T, typename... Args> 
void streamPrintf(const char *s, T value, Args... args) 
{ 
while (*s) { 
    if (*s == '%') { 
     if (*(s + 1) == '%') { 
      ++s; 
     } 
     else { 
      std::cout << value; 
      streamPrintf(s + 1, args...); 
      return; 
     } 
    } 
    std::cout << *s++; 
} 
throw std::logic_error("extra arguments provided to printf"); 
} 

void streamPrintf(const char *s) 
{ 
while (*s) { 
    if (*s == '%') { 
     if (*(s + 1) == '%') { 
      ++s; 
     } 
     else { 
      throw std::runtime_error("invalid format string: missing arguments"); 
     } 
    } 
    std::cout << *s++; 
    } 
} 

Но он печатает только мусор. Основная причина использования этого заключается в том, что я могу распечатать std :: string. Как распечатать правильные значения?

Я называю функция, как это:

logDebug("Event is, event=%", value); 

Peter T нашел проблему с помощью чата. Он не печатает uint8_t правильно, поскольку он рассматривает его как ASCII. Он должен быть литой типа, например. uint16_t. Когда у меня будет решение, я отправлю его здесь.

+0

Вы компилировать со всеми предупреждениями и отладочной информацией ('НКА -s = C++ 11 - Wall -g')? Вы использовали отладчик ('gdb')? –

+0

Да, у меня есть все эти флаги. – user1876942

+1

Выглядит просто [отлично] (http://coliru.stacked-crooked.com/a/3cb5daa3767e0984) для меня. – Columbo

ответ

1

Хороший пример использования VARIADIC шаблонов с Printf можно найти здесь:

http://msdn.microsoft.com/en-us/library/dn439779.aspx

void print() { 
    cout << endl; 
} 

template <typename T> void print(const T& t) { 
    cout << t << endl; 
} 

template <typename First, typename... Rest> void print(const First& first, const Rest&... rest) { 
    cout << first << ", "; 
    print(rest...); // recursive call using pack expansion syntax 
} 

int main() 
{ 
    print(); // calls first overload, outputting only a newline 
    print(1); // calls second overload 

    // these call the third overload, the variadic template, 
    // which uses recursion as needed. 
    print(10, 20); 
    print(100, 200, 300); 
    print("first", 2, "third", 3.14159); 
} 
+0

Ответы, которые имеют только ссылку, не очень хорошие; ссылки гниют. Попытайтесь хотя бы подытожить статью. –

+0

Спасибо, я добавил фрагмент кода –

Смежные вопросы