【问题标题】:Templated type conversion operator =模板类型转换运算符 =
【发布时间】:2015-10-23 14:25:26
【问题描述】:

我正在尝试将 R 类型 T 转换为 R 类型 S,反之亦然。 operator = 转换在简单的赋值中可以正常工作,但是当它尝试在初始化程序中使用它时,它会失败。为什么?

#include <array>

template<class T>
class Rectangle
{
public :

    Rectangle(T l, T t, T r, T b) : x1(l), y1(t), x2(r), y2(b) 
    {

    }

    template<class S>
    Rectangle<T> & operator = (Rectangle<S> const & o)
    {
        x1 = static_cast<T>(o.x1);
        y1 = static_cast<T>(o.y1);
        x2 = static_cast<T>(o.x2);
        y2 = static_cast<T>(o.y2);

        return *this;
    }

    T x1, y1, x2, y2;
};

int main(void)
{
    auto foo = Rectangle<float>(1.0f, 2.0f, 3.0f, 4.0f);
    auto bar = Rectangle<double>(1.0, 2.0, 3.0, 4.0);

    {
        foo = bar; // Converts, ok.
    }

    {
        auto arr = std::array<Rectangle<float>, 2>() = {{ 
            foo, 
            bar // Error - no appropriate default constuctor
        }};
    }

    return 0;
}

编辑:我使用的是 Visual Studio 2013。

【问题讨论】:

    标签: c++ templates type-conversion


    【解决方案1】:

    这里有两个问题。第一:

    auto arr = std::array<Rectangle<float>, 2>() = ...
    

    Rectangle&lt;T&gt; 不是默认可构造的,因此 () 将不起作用。无论如何,鉴于第二个=,我怀疑这只是一个错字。一旦你解决了这个问题:

        auto arr = std::array<Rectangle<float>, 2>{{ 
            foo, 
            bar // Still error
        }};
    

    现在,您有一个赋值运算符,但我们没有进行赋值。我们正在建设。所以你需要的是一个构造函数:

    template <class S>
    Rectangle(Rectangle<S> const& o)
        : x1(o.x1)
        , y1(o.y1)
        , x2(o.x2)
        , y2(o.y2)
    { }
    

    【讨论】:

    • 我看到你的答案是可能正确的,也许我使用 Visual Studio 2013 的事实是这里的问题。我尝试了构造函数,它没有任何区别。删除 = 是一个语法错误(“预期为 ;”)。
    • @Robinson 有两个=s 显然是错误的。你有auto x = T() = {{...}};,它正在尝试分配一个右值。可能是 VS13 不支持正确的大括号初始化?我不熟悉它的局限性。
    • 我不这么认为,不。我必须像这样初始化 std::array 。我稍后会尝试 2015 年。
    【解决方案2】:

    你需要的是转换“复制”构造函数

    template<class S>
    Rectangle(Rectangle<S> const & o) : Rectangle(o.x1, o.x2, o.y1, o.y2)
    

    当你编写如下代码时:

    A x = {a};
    

    您实际上使用的是构造函数(以a 作为参数),而不是赋值运算符。

    【讨论】:

      【解决方案3】:

      要使 A 类可转换为 B 类,您需要定义一个转换运算符,而不是赋值运算符。

      例子:

      operator B() {
         B b;
         b.populate_from(this);
         return b;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-01-16
        • 2013-05-05
        • 2015-07-22
        • 1970-01-01
        • 2011-12-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多