gpt4 book ai didi

c++ - 模板继承和运算符

转载 作者:搜寻专家 更新时间:2023-10-31 01:06:28 25 4
gpt4 key购买 nike

我有以下代码,当我在 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<>是一些元代码计算 T 是否是受支持的基本类型。 TypeFamily<T>::value如果 T 是 float ,则为 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=;
};

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

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