繁体   English   中英

定义自己的显式转换

[英]Defining your own explicit conversions

假设,如果不能通过显式强制转换(例如static_cast从一种类型转换为另一种类型,是否可以为其定义显式转换运算符?

编辑

我正在寻找一种定义以下内容的显式转换运算符的方法:

class SmallInt {

public:

    // The Default Constructor
    SmallInt(int i = 0): val(i) {
        if (i < 0 || i > 255)
        throw std::out_of_range("Bad SmallInt initializer");
    }

    // Conversion Operator
    operator int() const {
        return val;
    }

private:
    std::size_t val;

};

int main()
{
     SmallInt si(100);

     int i = si; // here, I want an explicit conversion.
}

对于用户定义的类型,您可以定义类型转换运算符 运算符的语法是

operator <return-type>()

您还应该知道,隐式类型转换运算符通常会被皱眉,因为它们可能使编译器有太多的回旋余地并导致意外的行为。 相反,您应该在类中定义to_someType()成员函数以执行类型转换。


对此不确定,但我相信C ++ 0x允许您指定explicit式类型强制转换,以防止隐式类型转换。

在当前标准中,从您的类型到其他类型的转换不能标记为explicit ,这在某种程度上是有意义的:如果要显式转换,则始终可以提供实现该转换的函数:

struct small_int {
   int value();
};
small_int si(10);
int i = si.value();   // explicit in some sense, cannot be implicitly converted

话又说回来,它可能没有太大的意义,因为在即将到来的标准,如果你的编译器支持的话,您可以标记转换操作符是explicit

struct small_int {
   explicit operator int();
};
small_int si(10);
// int i = si;                 // error
int i = (int)si;               // ok: explicit conversion
int j = static_cast<int>(si);  // ok: explicit conversion

如果这是您想要的,则可以定义转换运算符,例如:

void foo (bool b) {}

struct S {
   operator bool () {return true;} // convert to a bool
};

int main () {
   S s;
   foo (s);  // call the operator bool.
}

尽管实际上不建议使用这种隐式转换,因为一旦定义它,它可能会在您不期望的尴尬之处发生。

暂无
暂无

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

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