简体   繁体   English

转换运算符重载

[英]Conversion operator overloading

I want to distinguish a template conversion operator between &, * and values:我想区分 &、* 和值之间的模板转换运算符:

struct S
{
    template <class T>
    constexpr operator T()
    {
        return value;
    }
    template <class T>
    constexpr operator T&()
    {
        return value;
    }
    template <class T>
    constexpr operator T*()
    {
        return &value;
    }
    int value;
} s{5};

int main()
{
    uint32_t ui = s; // error:  error C2440: 'initializing': cannot convert from 'S' to 'uint32_t
}

If I remove constexpr operator T&() the code compiles and ui = s invokes the constexpr operator T() operator.如果我删除constexpr operator T&()代码编译并且ui = s调用constexpr operator T()运算符。 But why?但为什么?

I also get strange behaviour when I add the explicit specifier to those funcitons.当我向这些函数添加显式说明符时,我也会出现奇怪的行为。

It looks like the behaviour of the conversion operator differs from normal overloading.看起来转换运算符的行为与正常重载不同。 May anyone explain this?有人可以解释一下吗?

PS: I'm using VS2017 PS:我使用的是VS2017

Since value is of type int , it does not make sense to create a template conversion to a template parameter reference type.由于value的类型为int ,因此创建到模板参数引用类型的模板转换是没有意义的。 If the type is not int , you have a semantic error of trying to coerce an int object to a reference of some other type.如果类型不是int ,则尝试将int对象强制为其他类型的引用时会出现语义错误。

Redefine the reference conversion to the proper types:将引用转换重新定义为正确的类型:

constexpr operator int&()
{
    return value;
}
constexpr operator const int&() const
{
    return value;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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