2011-08-31 78 views
2

假设,如果从一种类型的另一种类型的转换是无法通过显式转换e.g 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. 
} 
+0

显式转换运算符就是返回目标类型的方法。或者我错过了什么? –

回答

3

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

operator <return-type>() 

你也应该知道,隐式类型转换操作符,一般在因为它们可能让编译器太多的回旋余地,并导致意外的行为皱起了眉头。相反,您应该在类中定义to_someType()成员函数来执行类型转换。


不知道这一点,但我相信的C++ 0x允许你指定一个类型转换为explicit防止隐式类型转换。

+0

确实! http://www2.research.att.com/~bs/C++0xFAQ.html#explicit-convertion – Dawson

+0

@Toolbox哪些编译器实现了C++ 11的这一特性?我不认为MSVC++ 2010有。 –

+0

@Seth Carnegie根据http://gcc.gnu.org/projects/cxx0x.html,显式转换运算符在GCC 4.5中可用。我没有能够自己测试这个。 – Dawson

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

虽然并不推荐使用,因为一旦确定,可能会出现尴尬的地方,隐式转换,你别指望它。

+0

是的,但是我可以将其变为仅接受显式转换吗? – Jason

+0

我在C++ 0x中这么认为,正如上面的答案所述。你为什么不定义一个'to_XXX'成员函数? –

+1

请注意隐式转换为bool。 http://stackoverflow.com/q/6242296/46642 –

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