jeudi 25 juin 2020

function overload with template specialization

This is one answer i see and got confused

template<typename T>
class A{
   public:

    explicit A(T x=0, uint32_t others=1) :
        m_obj((int64_t)x), m_others(others) {}

    A(const A& x) :
        m_obj(x.m_obj),
        m_bitWidth(x.others) {
    }


    A& operator=(const T& x) &  //for lvalue assignment 
    {
        m_obj = x;
        return *this;
    }

    A& operator=(const A& x) { //specialized? overload? for A type objects
        if(x != this) {
            m_obj = x.m_obj;
            m_others = x.m_others;
        }
        return *this;
    }
    double m_obj;
    double m_others;

};

The reason I have operator=(T& x) and operator=(const A& x) is because I want to be able to do the following:

A a;
A b(10,20);
int c = 10;

a = b;
a = 10;

I got confused by reading the answer above, because some answer says that without explicit specialization, the overload will never be used. However, in my case, my code is working fine as I tried. So my question would be :

  1. is there anything wrong with the code? should I use explicit specialization on A& operator=(const A& x)?
    template<>
    A& operator=(const A& x) { //specialized? overload? for A type objects
        if(x != this) {
            m_obj = x.m_obj;
            m_others = x.m_others;
        }
        return *this;
    }

Aucun commentaire:

Enregistrer un commentaire