2012-02-05 65 views
0

大家好日子!C++:範本:部分專精:打印一切模板

具有下面的代碼:

template<typename T, typename OutStream = std::ostream> 
struct print 
{ 
    OutStream &operator()(T const &toPrint, OutStream &outStream = std::cout) const 
    { 
     outStream << toPrint; 
     return outStream; 
    } 
}; 

template<typename T, typename Index = unsigned int, typename CharType = char, typename OutStream = std::ostream> 
struct print<T *, Index> 
{ 
    print(CharType delimiter = ' '): delimiter_(delimiter) {} 
    OutStream &operator()(T const *toPrint, Index startIndex, Index finishIndex, OutStream &outStream = std::cout) const 
    { 
     for (Index i(startIndex) ; i < finishIndex ; ++i) 
      outStream << toPrint[i] << delimiter_; 
     return outStream; 
    } 
protected: 
    CharType delimiter_; 
}; 

編譯:MSVCPP10

編譯器輸出:

1>main.cpp(31): error C2764: 'CharType' : template parameter not used or deducible in partial specialization 'print<T*,Index>' 
1>main.cpp(31): error C2764: 'OutStream' : template parameter not used or deducible in partial specialization 'print<T*,Index>' 
1>main.cpp(31): error C2756: 'print<T*,Index>' : default arguments not allowed on a partial specialization 

我卡住了。幫助我完成部分專業化。

謝謝!

+3

我您可能感興趣的[漂亮的打印圖書館(HTTP: //stackoverflow.com/questions/4850473/pretty-print-c-stl-containers)? – 2012-02-05 19:42:05

+0

你只能專門研究一些*更專業化的案例。你的'T *,索引'形式不是「更特別」,它完全不同。 – 2012-02-05 19:44:11

+0

@KerrekSB謝謝,您建議的項目非常有趣! – DaddyM 2012-02-05 19:48:39

回答

1

我想這是你的意思:(這可能是不正確的代碼,我只是想翻譯你寫的)

template<typename T> struct print<T*, unsigned int> { 
    typedef unsigned int Index; 
    typedef std::ostream OutStream; 
    typedef char CharType; 
    print(CharType delimiter = ' '): delimiter_(delimiter) {} 
    OutStream &operator()(T const *toPrint, Index startIndex, Index finishIndex, OutStream &outStream = std::cout) const { 
    for (Index i(startIndex) ; i < finishIndex ; ++i) 
     outStream << toPrint[i] << delimiter_; 
    return outStream; 
    } 
protected: 
    CharType delimiter_; 
}; 

編譯器解釋了什麼問題:

在部分專業化上不允許的默認參數

含義像typename Index = unsigned int這樣的東西只能出現在非專用模板中。

模板參數不使用或抵扣部分特例

這意味着你必須使用所有的參數在這一部分:struct print<HERE>

+0

太棒了!有用! – DaddyM 2012-02-05 20:18:03