2.6.2 Explicit Conversion Operators

Conversion operators can now be declared as explicit, to avoid unexpected conversions:

// This struct wraps an 8 bits non-negative integer value. 
struct custom_uint8 { /*  */ }; 
 
// This struct wraps a 64 bits signed integer value. 
struct custom_int64 { /*  */ }; 
 
// This struct wraps a 32 bits integer value. 
struct custom_int32 
{ 
  // This operator is explicit, as information may be lost when 
  // truncating to 8 bits. Thus we don’t want it to happen silently. 
  explicit operator custom_uint8() const 
  { 
    return custom_uint8(m_value); 
  } 
 
  // This operator is implicit, as all signed 32 bits values can be 
  // represented in a signed 64 bits. 
  operator custom_int64() const 
  { 
    return custom_int64(m_value); 
  } 
 
private: 
  int32_t m_value; 
}; 
 
void foo() 
{ 
  custom_uint8 i8; 
  custom_int32 i32; 
  custom_int64 i64; 
 
  // This is ok thanks to the implicit conversion operator. 
  i64 = i32; 
 
  // This won’t work since there is an implicit conversion. 
  i8 = i32; 
 
  // Here the conversion is explicit, so it will work. 
  i8 = static_cast<custom_uint8>(i32); 
}