简体   繁体   English

定义自己的显式转换

[英]Defining your own explicit conversions

Suppose, if a conversion from one type another type is not available through explicit casts eg static_cast , Would it be possible to define explicit conversion operators for it? 假设,如果不能通过显式强制转换(例如static_cast从一种类型转换为另一种类型,是否可以为其定义显式转换运算符?

Edit : 编辑

I'm looking for a way to define explicit conversion operators for the following: 我正在寻找一种定义以下内容的显式转换运算符的方法:

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.
}

For user defined types you can define a type cast operator . 对于用户定义的类型,您可以定义类型转换运算符 The syntax for the operator is 运算符的语法是

operator <return-type>()

You should also know that implicit type cast operators are generally frowned upon because they might allow the compiler too much leeway and cause unexpected behavior. 您还应该知道,隐式类型转换运算符通常会被皱眉,因为它们可能使编译器有太多的回旋余地并导致意外的行为。 Instead you should define to_someType() member functions in your class to perform the type conversion. 相反,您应该在类中定义to_someType()成员函数以执行类型转换。


Not sure about this, but I believe C++0x allows you to specify a type cast is explicit to prevent implicit type conversions. 对此不确定,但我相信C ++ 0x允许您指定explicit式类型强制转换,以防止隐式类型转换。

In the current standard, conversions from your type to a different type cannot be marked explicit , which make sense up to some extent: if you want to explicitly convert you can always provide a function that implements the conversion: 在当前标准中,从您的类型到其他类型的转换不能标记为explicit ,这在某种程度上是有意义的:如果要显式转换,则始终可以提供实现该转换的函数:

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

Then again, it might not make that much sense, since in the upcoming standard, if your compiler supports it, you can tag the conversion operator as explicit : 话又说回来,它可能没有太大的意义,因为在即将到来的标准,如果你的编译器支持的话,您可以标记转换操作符是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

If this is what you want, you can define conversion operators, eg: 如果这是您想要的,则可以定义转换运算符,例如:

void foo (bool b) {}

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

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

Although it is not really recommended because once defined, such implicit conversion can occur in awkward places where you don't expect it. 尽管实际上不建议使用这种隐式转换,因为一旦定义它,它可能会在您不期望的尴尬之处发生。

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

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