tags:

views:

81

answers:

2

Is there an C++ casting operator (or combination thereof) equivalent to the old-style cast below:

struct MyStruct {
   int i;
   int j;
   int k;
};

void do_something_with_mystruct( MyStruct ms ) {
   ...
};

int main( int argc, char** argv ) {
   do_something_with_mystruct( (MyStruct){1,2,3} );
};
A: 

The equivalent to the C style cast is:

reinterpret_cast<ToType>(fromType);

It does a blind conversion of the bit pattern. Unsafe in most cases, useful when you need it.

David
care to offer an example that compiles? Because I tried that and it generates a compiler error.
m1tk4
@m1tk4: probably because the `< >`'s were missing due to bad code formatting. I edited the answer
jalf
they weren't in my code - I tried it before posting the question.
m1tk4
@David: You misunderstood the question. See my response.
Zack
@Zack, I know. I was trying to edit my response before I got slapped. Having two unrelated people have the same response at the same time also points to value the error in interpretation.
David
+4  A: 

The construct

(MyStruct) {1,2,3}

is not actually a cast! It's an ISO C99 "compound literal". There is no equivalent using any of the C++ *_cast<> operators, because C++ (even C++0x) does not include this construct. Some compilers implement it as an extension to C++, but you still have to write it this way. See for instance http://gcc.gnu.org/onlinedocs/gcc-4.4.4/gcc/Compound-Literals.html.

Zack
awesome, thank you. I learned something new today.
m1tk4
C++0x includes the same functionality as `MyStruct{1,2,3}`, without the parens around the type. I believe you are allowed to arbitrarily add parens around such a type specifier, so yes, `(MyStruct) {1,2,3}` is valid C++0x.
Potatoswatter
It does? I couldn't find it in my copy of the draft standard, do you happen to know where it's specified?
Zack
@Zack: @Potato is right, check out §8.5.4 "List-initialization".
GMan