tags:

views:

183

answers:

5

In c# you can use as to convert a type or get null:

Object o = Whatever();
String s = o as String;

Is there a similar easy way to achieve this in c++? I'm using Visual Studio 2010, if thats important.

[update] Remember, there is a very important difference between casting and using as. Casting (at least in c#) will throw an exception if the type does not match:

Object o = null;
String s = (String)o; // will crash.
+3  A: 

use dynamic_cast<type>(), but it will only work with pointers, not static objects

knittl
With pointers, you get a null pointer if the cast is invalid. It works with references, but throws an exception if invalid.
Pontus Gagge
+8  A: 

In C++, this would be a dynamic_cast, if you had a hierarchy where Object is the parent and String is the child.

Object * p = createMyObject();
String * s = dynamic_cast<String *>(p);
if(s)
{
  ...
}

Dynamic casting a pointer will return a pointer to the object if the cast is possible, or a null pointer if not.

Also, dynamic casting a reference will return a reference to the object if the cast is possible, or throw an exception.

small_duck
Your syntax is wrong. should be: `dynamic_cast<String*>(p);` and you should note that String must be derived from Object.
anon
Indeed, I added the pointer.
small_duck
As an extension to what Neil said, there is no common base class that all classes in C++ automatically derive from. Some libraries do have such a central class, like Qt and wxWidgets, but these are explicitly derived from, either directly or through another class.
blwy10
C#'s `as` keyword is a conversion, not a cast.
John Dibling
+5  A: 

In C++ there is no base object class, so in general there is no way of doing this. You can however do it for specific hierarchies:

struct A {
   virtual ~A() {}
};

struct B : public A {
};

A * p = Something();     // Something() may return an A * or a B *
B & b = dynamic_cast <B&>(*p);

The dynamic cast will throw an exception if p does not point at something that can safely be converted to a B reference.

anon
just to confirm, can we dynamic_cast on reference?
lz_prgmr
@Dbger We certainly can.
anon
We should note the differences of casting a reference to casting a pointer. If the dynamic_cast fails: on a pointer then NULL is returned; on a reference an exception is thrown
Martin York
+2  A: 

From what I can read from: C# Programmer's Reference: AS the as operator performs the same task as dynamic_cast in C++.

TommyA
No, it most definitely does not. C#'s `as` is a conversion. dynamic_cast is a cast.
John Dibling
Considering this from the c# programmer's reference: *The as operator is like a cast except that it yields null on conversion failure instead of raising an exception.* And: `expression as type` is equivalent to: `expression is type ? (type)expression : (type)null`. I'd say the `as` operator is most resembling the `dynamic_cast` especially since `as` cannot perform user-defined conversions.
TommyA
@TommyA: I understand this, but the question is about an equivalent operation in C++, so even though it is not important to distinguish between 'cast' and 'convert' in a language like C#, there is a big difference in C++. So it is important to be clear. You said yourself, "as is like a cast" -- not "as *is* as cast." And the C# spec is equally explicit: (7.6.6) : "A cast-expression is used to explicitly convert an expression to a given type" and (7.9.11) : "The as operator is used to explicitly convert a value to a given reference type or nullable type" These are conversions, not casts.
John Dibling
An interesting note on the `as` keyword from the [MSDN: C# for C++ Developers](http://msdn.microsoft.com/en-us/library/yyaad03b%28VS.80%29.aspx): *The as keyword is similar to a standard cast, except that rather than throw an exception if the conversion fails, the return value is null. This is similar to using static_cast in C++, which, unlike dynamic_cast, performs no run-time check and hence does not throw an exception on failure.*
TommyA
A: 

In C# the as keyword converts a value to another type. There is code that supports this conversion (probably in the C# runtime). This is not a cast.

For the most part you can't use dynamic_cast or any other kind of cast in C++ to accomplish this, because casts and conversions are not the same thing. I say 'for the most part' because some types can be converted using static_cast, to convert an int to a float but this is still a conversion, not a cast. Also, if you have introduced a type system where everything is derived from an Object-like base class that has this conversion functionality, you might be able to construct a mechanism to support this conversion using dynamic_cast, but you would have had to write this mechanism and this does not seem to be what you're trying to do.

There is nothing built-in to C++ which will do this conversion for you; in other words, there is no C++ equivalent to the C# as keyword.

If you want to perform this conversion, you can often use streams:

#include <sstream>
#include <string>
#include <iostream>
using namespace std;

int main()
{
    float f = 42.0f;
    stringstream ss;
    ss << f;
    string s = ss.str();
    cout << "Float: " << f << ", String '" << s << "'";

    return 0;
}

<sstream> is part of the C++ Standard, so in this regard you might consider it to be 'in the language'.

Using streams to do this conversion can be rather clumsy. Boost offers lexical_cast which can be used to perform these simple conversions with less code:

#include <sstream>
#include <iostream>
#include <boost\lexical_cast.hpp>

using namespace std;

int main()
{
    string s = "42";
    float f = boost::lexical_cast<float>(s);

    cout << "Float: " << f << ", String '" << s << "'";

    return 0;
}
John Dibling
What is the difference between casting and converting a reference type in c#?
sylvanaar
@sylvanaar: In C# there seems to be no such thing as a true 'cast' in the C++ sense. In C++ a cast means "pretend variable x is of type Y", but according to the C# spec, (7.6.6) "A cast-expression is used to explicitly convert an expression to a given type." and (7.9.11) "The as operator is used to explicitly convert a value to a given reference type or nullable type. Unlike a cast expression (§7.6.6), the as operator never throws an exception. Instead, if the indicated conversion is not possible, the resulting value is null."
John Dibling
@sylvanaar: If you downvoted my answer, you must think it is wrong. What, exactly, is wrong in my post?
John Dibling
Why is using As on a reference type in c# not the same as using dynamic_cast on a pointer in C++? MS does mix their terms a little but the c# spec says "The as operator is like a cast operation. However, if the conversion is not possible, as returns null instead of raising an exception" I don't think you are correct in drawing such a strong distinction between cast/convert in this instance. But ill remove my downvote - just edit your post
sylvanaar
@sylvanaar: The downvote isn't the issue. The correctness of `as` being a cast is what I'm taking issue with here. The spec is explicit: (7.6.6) : "A cast-expression is used to explicitly convert an expression to a given type" and (7.9.11) : "The as operator is used to explicitly convert a value to a given reference type or nullable type" These are conversions, not casts.
John Dibling
Maybe its a confusion about what is being converted ... (6.2.4) "Reference conversions, implicit or explicit, never change the referential identity of the object being converted. In other words, while a reference conversion may change the type of the reference, it never changes the type or value of the object being referred to."
sylvanaar