Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
432 views
in Technique[技术] by (71.8m points)

c++ - R值的C ++隐式转换(C++ Implicit Conversion from R-Value)

I'm trying to define an implicit conversion operator that will move a wrapper type into the implicit type as such:

(我正在尝试定义一个隐式转换运算符,该运算符会将包装器类型移入隐式类型,例如:)

struct SomeStruct
{
    int a;
    int b;
    int c;
};

struct AnyStruct
{
    template <typename T>
    operator T&() &
    {
        return Get<T>();
    }

    template <typename T>
    operator T() &&
    {
        return std::move(Get<T>());
    }

    // details
    // ...
};

int main(void)
{
    SomeStruct s1 { 1, 2, 3 };
    AnyStruct s2 = std::move(s1);

    SomeStruct& s3 = s2;           // implicit conversion working
    SomeStruct s4 = std::move(s2); // implicit conversion not working (copying)
}

The first implicit conversion works and calls the right cast operator operator T&() & .

(第一个隐式转换起作用并调用正确的强制转换运算operator T&() & 。)

I would have expected the second implicit conversion to call the right cast operator operator T() && and move s2 into s4 , but it calls the cast operator operator T&() & instead and actually copy the struct.

(我本来希望第二次隐式转换调用正确的强制转换运算operator T() &&并将s2移至s4 ,但它会调用s2转换运算operator T&() &并实际上复制该结构。)

What am I doing wrong?

(我究竟做错了什么?)

  ask by sturcotte06 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...