【问题标题】:Templates inheritance and operators模板继承和运算符
【发布时间】:2013-12-23 10:42:20
【问题描述】:

当我在 Property 实例上调用 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&lt;&gt; 是一些元代码,用于计算 T 是否是受支持的基本类型。如果 T 是浮点数,TypeFamily&lt;T&gt;::value 为 0。

现在我创建一个聚合属性

// myNode.h.

class myNode
{
public:
    void setProp(float val) {m_prop = val;}

protected:
    Property<float> m_prop;
}

我最初认为Property&lt;float&gt; 派生自PropertyImpl&lt;float, 0&gt; 我可以调用m_prop = val,因为operator=() 是为PropertyImpl&lt;float, 0&gt; 定义的。但是我的编译器返回以下错误:

<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>        ]

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

有人知道发生了什么吗?

谢谢!

【问题讨论】:

    标签: c++ templates metaprogramming template-meta-programming


    【解决方案1】:

    Property 包含一个隐式声明的复制赋值运算符,它隐藏了基类中的那个。你需要一个 using-declaration 才能访问它:

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

    【讨论】:

    • template &lt;class T&gt; class Property : public PropertyImpl&lt;T&gt; {};not 继承 template &lt;class T&gt; class PropertyImpl&lt;T, 0&gt; : public PropertyBase {} 是否也有问题,正如 OP 所期望的那样?
    • @Johan 为什么不继承?
    • @Simple 它确实继承自 template &lt;class T, int typeFamily = TypeFamily&lt;T&gt;::value&gt; class PropertyImpl : public PropertyBase {}; 而不是从第二个继承。
    • @Johan:如果value 是零,如前所述,那么它从零的部分特化继承,如预期的那样。
    • @Johan 他说float 给出了typeFamily0TypeFamily&lt;T&gt;::value 的默认值不需要是专业化的一部分。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-14
    • 2020-03-27
    • 2011-07-08
    • 2023-04-02
    • 2020-12-10
    • 2021-04-24
    • 2011-12-05
    相关资源
    最近更新 更多