模板类方法的特化

编程入门 行业动态 更新时间:2024-10-08 08:33:00
本文介绍了模板类方法的特化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

假设我有以下课程:

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

private:
    T m_value;
};

如何为 T=float(或任何其他类型)编写函数的专用版本?

How can I write a specialized version of the function, for T=float (or any other type)?

注意:简单的重载是不够的,因为我只希望该函数可用于 T=float(即 MyClass::SetValue(float) 在这种情况下没有任何意义).

Note: A simple overload won't suffice because I only want the function to be available for T=float (i.e. MyClass::SetValue(float) doesn't make any sense in this instance).

推荐答案

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;
}

或者,如果您希望函数具有不同的签名

or, if you want the functions to have different signatures

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> {
};

这篇关于模板类方法的特化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-05-01 06:19:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1405387.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:特化   模板   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!