2012-10-13 87 views
6

假設我有下面的類的專業化:模板類方法

template <typename T> 
class MyClass 
{ 
public: 
    void SetValue(const T &value) { m_value = value; } 

private: 
    T m_value; 
}; 

我怎麼能寫功能的專用版本,爲T =浮動(或任何其他類型的)?

注意:一個簡單的重載是不夠的,因爲我只希望該函數可用於T = float(即MyClass :: SetValue(float)在這個實例中沒有任何意義)。

回答

8
template <typename T> 
class MyClass { 
private: 
    T m_value; 

private: 
    template<typename U> 
    void doSetValue (const U & value) { 
     std::cout << "template called" << std::endl; 
     m_value = value; 
    } 

    void doSetValue (float value) { 
     std::cout << "float called" << std::endl; 
    } 

public: 
    void SetValue(const T &value) { doSetValue (value); } 

}; 

或(模板偏特):

template <typename T> 
class MyClass 
{ 
private: 
    T m_value; 

public: 
    void SetValue(const T &value); 

}; 

template<typename T> 
void MyClass<T>::SetValue (const T & value) { 
    std::cout << "template called" << std::endl; 
    m_value = value; 
} 

template<> 
void MyClass<float>::SetValue (const float & value) { 
    std::cout << "float called" << std::endl; 
} 

,或者,如果你想要的功能有不同的簽名

template<typename T> 
class Helper { 
protected: 
    T m_value; 
    ~Helper() { } 

public: 
    void SetValue(const T &value) { 
     std::cout << "template called" << std::endl; 
     m_value = value; 
    } 
}; 

template<> 
class Helper<float> { 
protected: 
    float m_value; 
    ~Helper() { } 

public: 
    void SetValue(float value) { 
     std::cout << "float called" << std::endl; 
    } 
}; 

template <typename T> 
class MyClass : public Helper<T> { 
}; 
+0

您的部分模板專精答案擊中了頭部!正是我在找的,謝謝。 –

+0

實際上,在你的第二個例子中它是顯式的模板特化:你提供了1個模板參數中的所有1個,如果有的話,你需要提供2個。另一點是這些特殊的函數顯然如果將模板放入頭文件幷包含它兩次,則需要位於單獨的編譯單元(而不是頭文件)中。 – Markus

2

當然可以。只是,它應該是一個過載:)

template <typename T> 
class MyClass 
{ 
public: 
    template<class U> 
    void SetValue(const U &value) { m_value = value; } 
    void SetValue(float value) {do special stuff} 
private: 
    T m_value; 
}; 

int main() 
{ 
    MyClass<int> mc; 
    mc.SetValue(3.4); // the template member with U=double will be called 
    mc.SetValue(3.4f); // the special function that takes float will be called 

    MyClass<float> mcf; //compiles OK. If the SetValue were not a template, 
    // this would result in redefinition (because the two SetValue functions 
    // would be the same 
} 
+2

但是我只希望當T = float時浮子超載可用。否則,你可能有'MyClass :: SetValue(float)'這是沒有任何意義的。 –