gpt4 book ai didi

c++ - 继承模板赋值运算符

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:43:20 26 4
gpt4 key购买 nike

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

#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=使用它?

最佳答案

方法assign在你的类里面可见B因为你正在使用 struct它具有公共(public)默认封装和 public继承。

至于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.

关于c++ - 继承模板赋值运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25291603/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com