2013-04-09 17 views
-4

我是模板編程的初學者。在C++中看作是超載的專業化

我在模板三班模板功能:

// initialize the model (generic template for any other type) 
template <typename ImgDataType> 
void GrimsonGMMGen<ImgDataType>::InitModel(const cv::Mat& data) // data is an rgb image 
{ ... } 

template<> 
void GrimsonGMMGen<cv::Vec3b>::InitModel(const cv::Mat& data) 
{...} 

template<> 
void GrimsonGMMGen<float>::InitModel(const cv::Mat& data) 
{ ... } 

但我得到一個錯誤說有重複宣告指向 我記得使用這樣的專業化之前重新聲明它工作得很好。我在這裏做錯了什麼?

由於我設置的一些數據結構需要我使用的圖像類型的信息,所以我需要專門化它們。

+2

「*有重複聲明指向的*重聲明:」 我不明白。你能發佈完整的錯誤嗎? – 2013-04-09 22:22:53

+1

完整的錯誤和一個[簡短,獨立,正確(可編譯),例子](http://sscce.org/)。 – Oswald 2013-04-09 22:24:21

+0

作爲一個建議,嘗試避免功能模板的專業化,並選擇重載 – 2013-04-09 22:26:48

回答

1

你在這個問題中試圖做的事絕對有效:類模板的成員函數可以分別專門化(完全)。例如:

#include <iostream> 

template <typename T> struct Foo 
{ 
    void print(); 
}; 

template <typename T> void Foo<T>::print() 
{ 
    std::cout << "Generic Foo<T>::print()\n"; 
} 

template <> void Foo<int>::print() 
{ 
    std::cout << "Specialized Foo<int>::print()\n"; 
} 

int main() 
{ 
    Foo<char> x; 
    Foo<int> y; 

    x.print(); 
    y.print(); 
} 

Live demo