【问题标题】:Conversion between 2 template types2种模板类型之间的转换
【发布时间】:2014-02-08 07:56:24
【问题描述】:

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

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

【问题讨论】:

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


    【解决方案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 赋值运算符或提供足够的 getter。

    【讨论】:

      【解决方案2】:

      添加构造函数

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

      【讨论】:

      • 什么是Type2?你的意思是typename Type2
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-04
      • 1970-01-01
      • 1970-01-01
      • 2021-01-27
      • 2015-10-08
      相关资源
      最近更新 更多