定义您自己的显式转换

时间:2011-08-31 01:24:45

标签: c++ type-conversion explicit

假设,如果通过显式转换(例如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.
}

3 个答案:

答案 0 :(得分:3)

对于用户定义的类型,您可以定义type cast operator。运算符的语法是

operator <return-type>()

您还应该知道隐式类型转换运算符通常不受欢迎,因为它们可能会让编译器留有太多余地并导致意外行为。相反,您应该在类中定义to_someType()成员函数来执行类型转换。


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

答案 1 :(得分:2)

在当前标准中,从您的类型到另一种类型的转换无法标记为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

答案 2 :(得分:0)

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

void foo (bool b) {}

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

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

虽然不是真的推荐,因为一旦定义,这种隐式转换可能发生在您不期望的尴尬的地方。