2014-01-19 95 views
1

我有这段代码一类(这是一个片段):之间的转换2模板

template<typename T> 
class Pos2 { 
public: 
    T x, y; 

    Pos2() : x(0), y(0) {}; 
    Pos2(T xy) : x(xy), y(xy) {}; 
    Pos2(T x, T y) : x(x), y(y) {}; 

}; 

现在,我也得到了2种类型定义它:

typedef Pos2<pos_scalar> Pos; 
typedef Pos2<size_scalar> Size; 

一切正常,但是当我这样做:

Pos p(5.5, 6.5); 
Size s(3, 8); 
p = s; 

我得到这个错误:

error: conversion from ‘Size {aka Pos2<short int>}’ to non-scalar type ‘Pos’ requested 

这是有道理的,但我想知道如何解决它= P

回答

2

添加一个构造函数

template <typename Type2> Pos2(const Pos2<Type2> &other) 
{ x = other.x; y = other.y; } 
+1

什么是'Type2'?你的意思是'typename Type2'? – 0x499602D2

1

你需要从Size类型定义赋值运算用于分配给输入Pos,因为它们不是相同的类型,因此两者之间没有默认的赋值运算符。

我猜你想在这里使用模板,所以Pos2任何实例可用于分配给另一个实例。例如像这样:

template<typename T> 
class Pos2 { 
public: 
    T x, y; 

    Pos2() : x(0), y(0) {}; 
    Pos2(T xy) : x(xy), y(xy) {}; 
    Pos2(T x, T y) : x(x), y(y) {}; 

    template<typename FromT> 
    Pos2<T>& operator=(const Pos2<FromT>& from) { 
     x = from.x; 
     y = from.y; 
     return *this; 
    } 
}; 

你应该做的拷贝构造函数(此处未示出)一样,因为它可能会发生,你要复制构建在某一时刻相同的方案。

如果T型和FromT之间的分配,即pos_scalarsize_scalar可能这不只是工作。如果不尝试为赋值运算符添加正确的显式转换和/或模板特化。

此外,如果Pos2的任何成员是私人/受保护的,您将需要friend转让运营商或提供足够的获得者。