2种模板类型之间的转换 [英] Conversion between 2 template types

查看:230
本文介绍了2种模板类型之间的转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类的这段代码(这是一个代码段):

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

};

现在,我还有2个typedef:

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;

我收到此错误:

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

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

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

推荐答案

添加构造函数

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

这篇关于2种模板类型之间的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆