【发布时间】: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<> 是一些元代码,用于计算 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> ]
这对我来说完全不清楚,我感觉我错过了模板的基本行为。或者它很容易就在我眼前......
有人知道发生了什么吗?
谢谢!
【问题讨论】:
标签: c++ templates metaprogramming template-meta-programming