继承的模板赋值运算符

时间:2014-08-13 16:37:19

标签: c++ templates inheritance c++11 using

在使用其父模板方法之一编写子类时,我经常遇到编译问题。例如,我写了这个,但我不知道它为什么编译:

#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();
}

如果我想将此运算符与using A<T,N>::operator=;的实例一起使用,则必须包含语句B<T,N>,但我从未指定方法assign应该是可见的。它是否可见,因为operator=使用它?

1 个答案:

答案 0 :(得分:2)

方法assign在您的班级B中可见,因为您正在使用具有公共默认封装和struct继承的public

至于operator=

  

(13.5.3赋值)赋值运算符应由a实现   只有一个参数的非静态成员函数。因为副本   赋值运算符operator =是为类隐式声明的   用户未声明,基类赋值运算符始终是   由派生类的复制赋值运算符隐藏。

相关问题