2014-10-06 180 views
0

我得到了一些示例代碼從這裏做一個C++可變參數模板:C++ 11可變參數模板

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); 

彼得牛逼通過聊天發現了這個問題。它不會正確打印uint8_t,因爲它將它視爲ASCII。它需要被輸入到例如uint16_t。當我有解決方案時,我會在這裏發佈。

+0

你所有的警告和調試信息(編譯'GCC -std = C++ 11 - 牆-g')?你使用了調試器('gdb')嗎? – 2014-10-06 11:08:44

+0

是的,我擁有所有這些標誌。 – user1876942 2014-10-06 11:13:08

+1

看起來[罰款](http://coliru.stacked-crooked.com/a/3cb5daa3767e0984)給我。 – Columbo 2014-10-06 11:14:53

回答

1

一個很好的例子,使用可變參數模板用的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

只有鏈接的答案不是很好;鏈接腐爛。儘量至少總結文章。 – 2014-10-06 12:27:17

+0

謝謝,我添加了代碼片段 – 2014-10-06 13:30:20