Search code examples
c++templatesinheritancec++11using

Inherited template assignment operator


I often run into compiling issues when writing a child class using one of its parent's template method. For example, I wrote this, but I don't know why it compiles:

#include <iostream>
#include <type_traits>
#include <algorithm>

        /********************     **********     ********************/

template <class T, unsigned N>
struct A
{
    T data[N];

    template <class U>
    inline auto operator= ( const U& other ) -> decltype(*this)
        { this->assign(other); return *this; }

    template <class U>
    void assign( const U& other )
        { assign_impl( other, std::is_arithmetic<U>() ); }

    template <class U>
    void assign_impl( const U& val, std::true_type const )
        { std::fill( data, data+N, static_cast<T>(val) ); }
};

// ------------------------------------------------------------------------

template <class T, unsigned N>
struct B
    : public A<T,N>
{
    // Needed in order to compile
    using A<T,N>::operator=;

    void show()
    {
        for (unsigned i=0; i<N; ++i)
            std::cout<< this->data[i] << " ";
            std::cout<< std::endl;
    }
};

// ------------------------------------------------------------------------

int main()
{
    B<double,5> b;
    b = -5.1; 
    b.show();

    b.assign(3.14159);
    b.show();
}

Including the statement using A<T,N>::operator=; is necessary if I want to use this operator with instances of B<T,N>, but I never specified that the method assign should be visible. Is it visible because operator= uses it?


Solution

  • The method assign is visible in your class B because you are using struct which has public default encapsulation and public inheritance.

    As for operator= :

    (13.5.3 Assignment) An assignment operator shall be implemented by a non-static member function with exactly one parameter. Because a copy assignment operator operator= is implicitly declared for a class if not declared by the user, a base class assignment operator is always hidden by the copy assignment operator of the derived class.