How can I overload an operator for a class with a common template?

Suppose we have some templated class B:

template<class T>
class B {
public:
    B(void) { (void)static_cast<C*>((T*)0) }
    ~B(void) {}
    unsigned as_int(void) { return this->internal_state; }
private:
    unsigned internal_state;
}

      

whose template accepts class C and its derived classes (due to the static cast in the constructor above):

class C {
    //something
}

class D
    : public C {
    //something
}

      

If then we have a third class A:

class A {
public:
    A(void) { //something };
    ~A(void) { //something };

    inline A& operator = (B<C>& rhs) { this->internal_state = rhs.as_int(); }
    inline A& operator = (B<D>& rhs) { this->internal_state = rhs.as_int(); }
private:
    unsigned internal_state;
}

      

What I want to do is to provide an overload of an assignment operator that takes class B as the right hand side. In the snippet above, this works fine, but only if I overload for each B template separately (B, B, etc.). Is it possible to overload once for some common B

+3


source to share


1 answer


Two comments. First, if you only want B to be templated in C and it's children, you should just do static_assert:

std::static_assert(std::is_base_of<C, T>::value, "Error: T not child of C!")

      



Second, you can write a generic assignment operator as suggested:

template <typename T>
A& operator= (B<T> & rhs) { ... } // inline implied inside class declaration

      

+2


source







All Articles