2010-08-27 62 views
2

下面的代碼編譯正確。模板專業化:非內聯函數的定義問題

#include <string> 

template <typename T, typename U> 
class Container 
{ 
private: 
    T value1; 
    U value2; 
public: 
    Container(){} 
    void doSomething(T val1, U val2); 
}; 

template<typename T, typename U> 
void Container<typename T, typename U>::doSomething(T val1, U val2) 
{ 
    ; // Some implementation 
} 

template <> 
class Container<char, std::string> 
{ 
private: 
    char value1; 
    std::string value2; 
public: 
    Container(){} 
    void doSomething(char val1, std::string val2) 
    { 
     ; // Some other implementation 
    } 
}; 

但是,如果我嘗試之外定義void doSomething(char val1, std::string val2),我碰到下面的錯誤。

#include <string> 

template <typename T, typename U> 
class Container 
{ 
private: 
    T value1; 
    U value2; 
public: 
    Container(){} 
    void doSomething(T val1, U val2); 
}; 

template<typename T, typename U> 
void Container<typename T, typename U>::doSomething(T val1, U val2) 
{ 
    ; // Some implementation 
} 

template <> 
class Container<char, std::string> 
{ 
private: 
    char value1; 
    std::string value2; 
public: 
    Container(){} 
    void doSomething(char val1, std::string val2); 
}; 

template<> 
void Container<char,std::string>::doSomething(char val1, std::string val2) 
{ 
    ; // Some other implementation 
} 

錯誤:

Error 1 error C2910: 'Container::doSomething' : cannot be explicitly specialized c:\users\bharani\documents\visual studio 2005\projects\templates\template specialization\templatespecializationtest.cpp 35

我犯了什麼錯誤?

謝謝。

回答

6

您還沒有明確專業的成員函數。但是你正在定義顯式(類模板)專業化的成員函數。這是不同的,你需要定義它像

inline void Container<char,std::string>::doSomething(char val1, std::string val2) 
{ 
    ; // Some other implementation 
} 

注意的是,「內聯」是非常重要的,因爲這不是一個模板,它不隱式內聯如果定義在類外。如果將標題包含到多個翻譯單元中,則需要內聯以避免重複的鏈接程序符號。

你會在你明確的專業化模板,你的語法必須使用:

template <> 
class Container<char, std::string> 
{ 
private: 
    char value1; 
    std::string value2; 
public: 
    Container(){} 

    template<typename T, typename U> 
    void doSomething(T val1, U val2) { /* primary definition */ } 
}; 

template<> 
inline void Container<char,std::string>::doSomething(char val1, std::string val2) 
{ 
    ; // Some other implementation 
} 

你也有你的第一個代碼錯誤。您需要像這樣定義類外定義,而在類模板的參數列表中沒有「typename」

template<typename T, typename U> 
void Container<T, U>::doSomething(T val1, U val2) 
{ 
    ; // Some implementation 
} 
+0

非常感謝!它幫助! – bdhar 2010-08-27 17:14:25