C++ 模板类方法的特殊化

C++ 模板类方法的特殊化,c++,templates,C++,Templates,假设我有以下课程: template <typename T> class MyClass { public: void SetValue(const T &value) { m_value = value; } private: T m_value; }; 模板 类MyClass { 公众: void SetValue(const T&value){m_value=value;} 私人: T m_值; }; 如何为T=float(或任何其他类型)编写函

假设我有以下课程:

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

private:
    T m_value;
};
模板
类MyClass
{
公众:
void SetValue(const T&value){m_value=value;}
私人:
T m_值;
};
如何为T=float(或任何其他类型)编写函数的专用版本


注意:简单的重载是不够的,因为我只希望函数对t=float可用(即MyClass::SetValue(float)在本例中没有任何意义)。

当然可以。只是它应该是一个过载:)

模板
类MyClass
{
公众:
模板
void SetValue(const U&value){m_value=value;}
void SetValue(float value){do special stuff}
私人:
T m_值;
};
int main()
{
MyClass mc;
mc.SetValue(3.4);//将调用U=double的模板成员
mc.SetValue(3.4f);//将调用接受float的特殊函数
MyClass mcf;//编译正常。如果SetValue不是模板,
//这将导致重新定义(因为两个SetValue函数
//也一样
}
模板
类MyClass{
私人:
T m_值;
私人:
模板
无效剂量值(常数U和值){

std::cout但我只希望当T=float时float重载可用。否则,您可以使用
MyClass::SetValue(float)
这没有任何意义。你的部分模板专门化答案一针见血!正是我想要的,谢谢。实际上,在你的第二个示例中,这是显式的模板专门化:你提供了所有1/1模板参数另一点是,如果将模板放入头文件并包含两次,这些专用函数显然需要位于单独的编译单元(而不是头文件)中。
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   
}
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> {
};