假设我有以下类:
template <typename T>
class MyClass
{
public:
    void SetValue(const T &value) { m_value = value; }
private:
    T m_value;
};如何为T=float (或任何其他类型)编写函数的专用版本?
注意:简单的重载是不够的,因为我只想让函数对T=float可用(即MyClass::SetValue(float)在这个实例中没有任何意义)。
发布于 2012-10-14 16:14:53
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); }
};or (部分模板专门化):
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> {
};发布于 2012-10-14 06:11:44
你当然可以。只是它应该是一个重载:)
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   
}https://stackoverflow.com/questions/12877420
复制相似问题