简体   繁体   中英

Conversion between 2 template types

I've got this piece of code for a class (this is a snippet):

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) {};

};

Now, I've also got 2 typedefs for it:

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

Everything works as expected, but when I do this:

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

I get this error:

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

It makes sense, but I'd like to know how to fix it =P

Add a constructor

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

You need to define an assignment operator for assignment from type Size to type Pos , because these are not the same type and therefore there is no default assignment operator between the two.

I guess you want to use a template here, so any instantiation of Pos2 can be used to assign to another instantiation. For example like so:

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;
    }
};

You should do the same with the copy constructor (not shown here), because it might likely happen that you want to copy construct in the same scheme at some point.

This does only work if the assignment between type T and FromT , that is pos_scalar and size_scalar is possible. If not try to add correct explicit conversions and/or template specializations for the assignment operator.

Also if any of the members of Pos2 are private/protected you will need to friend the assignment operator or provide adequate getters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM