2012-01-06 75 views
0

我正在写一个有几个专业化的矢量模板,以便为矢量的前几个项目(如x,y,z,w)命名访问器,具体取决于尺寸。 KennyTM's answer对此非常有帮助。我还添加了一个Curiously recurring template pattern的形式,以便能够自然地使用操作员。这是基础类,并添加了功能的专业化(省略大部分成员实现为了简洁):CRTP和模板专业化的运营商的奇怪行为

template<int Dim, typename V, typename ItemType = float> 
class VectorImpl 
{ 
public: 
    typedef ItemType value_type;  
    VectorImpl() { elements.fill(0); }  
    VectorImpl(std::initializer_list<ItemType> init_list); 

     V operator+(const V& other) 
    { 
     V result; 
     for (int i = 0; i < Dim; ++i) 
      result.elements[i] = elements[i] + other.elements[i]; 

     return result; 
    } 

    QString toString();  
     // ... other members ... 

protected: 
    VectorImpl(const VectorImpl& other) = default; 

protected: 
    std::array<ItemType, Dim> elements; 
}; 

template<int Dim, typename ItemType = float> 
class Vector : public VectorImpl<Dim, Vector<Dim, ItemType>, ItemType> 
{ 
    typedef VectorImpl<Dim, Vector<Dim, ItemType>, ItemType> ParentType; 
public: 
    Vector() : ParentType() {} 
    Vector(const ParentType& other) : ParentType(other) {} 
    Vector(std::initializer_list<ItemType> init_list) : ParentType(init_list) {} 
}; 

template<typename ItemType> 
class Vector<3, ItemType> : public VectorImpl<3, Vector<3, ItemType>, ItemType> 
{ 
    typedef VectorImpl<3, Vector<3, ItemType>, ItemType> ParentType; 
public: 
    Vector() : ParentType() {} 
    Vector(const ParentType& other) : ParentType(other) {} 
    Vector(std::initializer_list<ItemType> init_list) : ParentType(init_list) {} 
    ItemType x() const { return this->elements[0]; } 
    ItemType y() const { return this->elements[1]; } 
    ItemType z() const { return this->elements[2]; } 
}; 

,我想补充qDebug()<<支持,所以我这样做:

template<int Dim, typename ItemType> 
QDebug operator<<(QDebug dbg, Vector<Dim, ItemType>& v) 
{ 
    dbg.nospace() << v.toString(); 
    return dbg.space(); 
} 

现在,下面的代码编译和工作原理:

Vector<3> v1 = { 3,4,5 }; 
qDebug() << v1; 

这一个呢,太:

Vector<3> v1 = { 3,4,5 }; 
Vector<3> v2 = { 1,-1,1 }; 
qDebug() << v1; 
auto v3 = v1 + v2; 
qDebug() << v3; 

但是这一次没有:

Vector<3> v1 = { 3,4,5 }; 
Vector<3> v2 = { 1,-1,1 }; 
qDebug() << (v1 + v2); 

编译器说:

error: no match for 'operator<<' in 'qDebug()() << v1.Vector<3>::.VectorImpl::operator+ [with int Dim = 3, V = Vector<3>, ItemType = float]((*(const Vector<3>*)(& v2)))'

这是怎么回事?分配给变量时为什么v1 + v2的类型不同?我应该怎样做才能编译?

回答

4

给输出功能的常量参考,或右值(如临时性的即是你的另外的结果)不会绑定到它(和也不会对实际的常量,对于这个问题):

QDebug operator<<(QDebug dbg, Vector<Dim, ItemType> const & v) 
//             ^^^^^ 

还宣布toString为const:

QString toString() const; 
//     ^^^^^ 
+0

我觉得这个问题(不做参考常数)出来了很多SO。 – 2012-01-06 02:24:44

+0

我不敢相信我错过了......谢谢! – 2012-01-06 02:24:50

+0

@TamásSzelei:发生在最好的...... :-) – 2012-01-06 02:27:55