两种模板类型之间的转换

时间:2014-01-19 01:24:52

标签: c++ class templates initialization type-conversion

我有一段课程的代码(这是一个片段):

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:

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 个答案:

答案 0 :(得分:2)

添加构造函数

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

答案 1 :(得分: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;
    }
};

您应该对复制构造函数(此处未显示)执行相同的操作,因为您可能希望在某个时刻复制构造在同一个方案中。

仅当类型TFromT之间的分配(pos_scalarsize_scalar成为可能时,此功能才有效。如果没有,请尝试为赋值运算符添加正确的显式转换和/或模板特化。

如果Pos2的任何成员都是私人/受保护的,您需要friend分配操作员或提供足够的获取者。