简体   繁体   中英

Implementation of C++ Cast

I was going through some code in CodeProject and came across the following code for C++ casting.

template <class OutputClass, class InputClass>
union horrible_union{
    OutputClass out;
    InputClass in;
};
template <class OutputClass, class InputClass>
inline OutputClass horrible_cast(const InputClass input){
    horrible_union<OutputClass, InputClass> u;
    u.in = input;
    return u.out;
}

Why is the cast implemented the above way. Why can't we just do a manual cast. Can someone give an example of when a normal cast wouldn't work ?

This approach basically lets you get away with any cast, although it relies on undefined behavior.

A normal cast would complain when casting between unrelated types, whereas this wouldn't.

struct A{};
struct B{};

template <class OutputClass, class InputClass>
union horrible_union{
    OutputClass out;
    InputClass in;
};
template <class OutputClass, class InputClass>
inline OutputClass horrible_cast(const InputClass input){
    horrible_union<OutputClass, InputClass> u;
    u.in = input;
    return u.out;
}

int main()
{
    A a;
    B b;
    a = horrible_cast<A,B>(b);   //this compiles
    a = reinterpret_cast<A>(b);  //this doesn't
} 

Bottom line: it's horrible, don't do it.

Using a union in this way is in general roughly equivalent to a hard reinterpret_cast of pointers. However, that doesn't copy objects, your example does (twice even with RVO, in fact; it would be rather more efficient to have const InputClass& input as the argument). So you can directly operate on its result without possibly mutating the original object.

What exactly this is useful for... hm. I don't think there's any really good use case, unchecked casts should always be avoided, and as David Hammen remarked this one is actually completely undefined (though it will normally work, if used "correctly").

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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