在类模板中重载赋值运算符 [英] Overloading assignment operator in a class template

查看:245
本文介绍了在类模板中重载赋值运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#ifndef NUMBER_HPP
#define NUMBER_HPP

template <class T>
class Number
{
public:
Number( T value ) : m_value( value )
{
}

T value() const
{
 return m_value;
}

void setValue( T value )
{
 m_value = value;
}

Number<T>& operator=( T value )
{
 m_value = value;
}

//  template <class T2>
//  Number<T2>& operator=( const Number<T>& number )
//  {
//    m_value = number.value();

//    return *this;
//  }

private:
 T m_value;
};

typedef Number<int> Integer;
typedef Number<char*> Float;

#endif // NUMBER_HPP

此模板类使用两个数据初始化类型分开。

This template class is initialized with two data types seperatly. one is int type and other is char pointer type.

   typedef Number<int> Integer1,Integer2;
   typedef Number<char*> Char1,Char2;
   Integer2.setValue(2) ;
   Char2.setValue("ABC");
   Integer1 = Interger2;//Case 1
   Char1 = Char2; // Case 2

在情况1中:
不需要深拷贝。

In case 1: Deep copy is not required.

在情况2中:
在复制指针时必须进行深拷贝。

In case 2: Deep copy is must as we are copying the pointers.

这些类使用赋值运算符的相同基本副本。我们如何实现呢?

But as both of the classes uses same base copy of assignment operator. how can we achieve this?

请提出一个不包含C ++ 11的解决方案。

Please suggest a solution which does not include C++ 11.

推荐答案

也许您只是想重载 operator = 的值:

Maybe you just want to overload your operator='s:

template <class T2>
Number<T>& operator=( const Number<T2*>& number )
{
    // Deep Copy
}

template <class T2>
Number<T>& operator=( const Number<T2>& number )
{
    // Shallow Copy
}

在其他所有情况下,您可能希望 std :: enable_if 根据类型静态决定使用哪个副本策略(最有可能是它是一个指针类型,因此例如 std :: is_pointer< T2> :: value )。然后可以很容易地通过如果constexpr (C ++ 17)来简化:

In probably all other cases you want std::enable_if to statically decide which copy stategy shall be used depending on the type (most likely whether it is a pointer type, therefore e.g. std::is_pointer<T2>::value). This can then very easily simplified by if constexpr (C++17):

#include <type_traits>

template <class T2>
Number<T>& operator=( const Number<T2>& number )
{
    if constexpr( std::is_pointer_v<T2> ){
        // Deep Copy
    }
    else{
        // Shallow Copy
    }
    return *this;
}

希望这会有所帮助!

这篇关于在类模板中重载赋值运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆