模板继承和运算符

Templates inheritance and operators

本文关键字:运算符 继承      更新时间:2023-10-16

我有以下代码,当我在属性实例上调用 operator=() 时会导致问题:

// myProperty.h.
template <class T, int typeFamily = TypeFamily<T>::value>
class PropertyImpl : public PropertyBase
{
    // Default template to catch errors.
};
template <class T>
class PropertyImpl<T, 0> : public PropertyBase
{
    // Data is part of the family of base types.
public:
    PropertyImpl(T* dataRef) : PropertyBase(), m_dataRef(dataRef) {}
    void operator=(T const & data) {*m_dataRef = data;}
protected:
    T* m_dataRef;
};
template <class T>
class Property : public PropertyImpl<T> {};

请注意,TypeFamily<>是一些元代码计算 T 是否为受支持的基类型。 如果 T 是浮点数,则TypeFamily<T>::value为 0。

现在我创建一个聚合属性

// myNode.h.
class myNode
{
public:
    void setProp(float val) {m_prop = val;}
protected:
    Property<float> m_prop;
}

我最初认为Property<float>PropertyImpl<float, 0>派生出来,我将能够调用m_prop = val,因为operator=()是为PropertyImpl<float, 0>定义的。但是我的编译器返回以下错误:

<myNode_path>(myNode_line) : error C2679: binary '=' : no operator found which takes a right-hand operand of type 'float' (or there is no acceptable conversion)
3>        <myProperty_path>(myProperty_line): could be 'Property<T> &Property<T>::operator =(const MPC::Property<T> &)'
3>        with
3>        [
3>            T=float
3>        ]
3>        while trying to match the argument list '(Property<T>, float)'
3>        with
3>        [
3>            T=float
3>        ]

这对我来说是完全不清楚的,我感觉我错过了模板的基本行为。或者它很容易在我眼前捕捉......

有人明白发生了什么吗?

谢谢!

Property包含一个隐式声明的复制赋值运算符,该运算符隐藏基类中的运算符。您需要一个 using 声明才能使其可访问:

template <class T>
class Property : public PropertyImpl<T> {
public:
    using PropertyImpl<T>::operator=;
};