1

I have the following 2 classes:

 class B; 
 class A
 {
     public:
     A();
     operator B() const;
  };
  class B
  {
     public:
     B2();
  };

here, A defines implicit conversion operator to B class. Then C++ reference says the following " If an implicit conversion sequence from new_type to the type of expression exists, that does not include lvalue-to-rvalue, array-to-pointer, function-to-pointer, null pointer, null member pointer, or boolean conversion, then static_cast can perform the inverse of that implicit conversion". It means that the following is to be compiled

  A a;
  B b=a;
  A a1=static_cast<A> (b);

but Xcode gives an error message

2
  • The latest standard(s) refer to "standard conversion" not "implicit conversion". I think that's important. This conversion is invalid.
    – david.pfx
    Aug 20, 2014 at 3:47
  • Actually, I found your wording on cppreference. Maybe it's from an outdated version of the standard? See en.cppreference.com/w/cpp/language/static_cast
    – david.pfx
    Aug 20, 2014 at 3:48

1 Answer 1

5

Your C++ reference is being imprecise. The Standard (C++14 §5.2.9/7) says,

The inverse of any standard conversion sequence (Clause 4) not containing an lvalue-to-rvalue (4.1), array-to-pointer (4.2), function-to-pointer (4.3), null pointer (4.10), null member pointer (4.11), or boolean (4.12) conversion, can be performed explicitly using static_cast.

Notice that it says standard conversion sequence. static_cast cannot perform the inverse of a user-defined conversion. It is also not hard to see why this is; if static_cast were required to perform the inverse of user-defined conversion sequences, it would have to have the ability to reverse arbitrary algorithms. For example, if A holds a pair of integers and B holds a single integer, and A::operator B() multiplies together the two integers, then the inverse would have to factor the integer in B...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.