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> {
};
您的部分模板專精答案擊中了頭部!正是我在找的,謝謝。 –
實際上,在你的第二個例子中它是顯式的模板特化:你提供了1個模板參數中的所有1個,如果有的話,你需要提供2個。另一點是這些特殊的函數顯然如果將模板放入頭文件幷包含它兩次,則需要位於單獨的編譯單元(而不是頭文件)中。 – Markus