C++template expression的问题


 #include<iostream>
 using namespace std;

 template <typename T,int size>
class Buffer{
 private:
    T b_array[size];
 public:
    T* getBuffer(){
        return b_array;
    }

    T& operator [](int index){
        return b_array[index];
    }

    void bprint(){
        cout<<getBuffer()<<endl;
    }

 };
 //为什么void Buffer<char,4>::bprint(){...}就可以?
 template<int size>
 void Buffer<char, size>::bprint(){
    cout << "Special input:" << getBuffer();
 }

 template<int size>
 void Buffer<int, size>::bprint(){
    for (int i = 0; i < size; i++){
        cout << b_array[i] << " ";
    }
 }

 int main(){
    Buffer<char,5> buffer;
    strcpy(buffer.getBuffer(), "Hello");
    buffer.bprint();
    cout << endl;

    Buffer<int, 4> buffer2;
    for (int i = 0; i < 4; i++){
        buffer2[i] = i + 1;
    }
    buffer2.bprint();
    getchar();
    getchar();
 }

为什么会出现这样的错误:
Error 6 error C2333: 'Buffer::bprint' : error in function declaration; skipping function body f:\work\c++\visual studio 2013\exam_review\exam_review\template.cpp 18 1 Exam_review
Error 7 error C2333: 'Buffer::bprint' : error in function declaration; skipping function body f:\work\c++\visual studio 2013\exam_review\exam_review\template.cpp 18 1 Exam_review
Error 4 error C2976: 'Buffer' : too few template arguments f:\work\c++\visual studio 2013\exam_review\exam_review\template.cpp 30 1 Exam_review
Error 2 error C2995: 'void Buffer::bprint(void)' : function template has already been defined f:\work\c++\visual studio 2013\exam_review\exam_review\template.cpp 30 1 Exam_review
Error 3 error C3855: 'Buffer': template parameter 'T' is incompatible with the declaration f:\work\c++\visual studio 2013\exam_review\exam_review\template.cpp 30 1 Exam_review
Error 1 error C3860: template argument list following class template name must list parameters in the order used in template parameter list f:\work\c++\visual studio 2013\exam_review\exam_review\template.cpp 30 1 Exam_review
Error 5 error C3860: template argument list following class template name must list parameters in the order used in template parameter list f:\work\c++\visual studio 2013\exam_review\exam_review\template.cpp 37 1 Exam_review

template
void Buffer::bprint(){
cout << "Special input:" << getBuffer();
}

template
void Buffer::bprint(){
for (int i = 0; i < size; i++){
cout << b_array[i] << " ";
}
}

兄弟,这段问题略大

Buffer buffer;
strcpy(buffer.getBuffer(), "Hello");
这段在strcpy里面 操作的 buffer.getBuffer() 返回的是 会消失,没有保存buffer的“Hello”值

已经解决了这个问题,问题在于:
只能特化类,不能特化模板类中的函数。
所谓特化就是把模板中的类型具体化,特化的syntax是这样的:
template <...>
...

所以在我的代码中

//这里是在特化模板类中函数, 不被允许
 template<int size>
 void Buffer<char, size>::bprint(){
    cout << "Special input:" << getBuffer();
 }

而这样是可以的

//这里不是在特化,因为没有template<...>...
 void Buffer<char,4>::bprint(){
    cout << "Special input:" << getBuffer();
 }