Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ equivalent of C# 4.0's "dynamic" keyword?

In C# 4.0, you can use the "dynamic" keyword as a placeholder for a type that is not known until runtime. There are certain corner cases where this is extremely useful behavior. Is it possible to emulate anything like this in C++, possibly using C++0x features or RTTI?

like image 427
Derek Thurn Avatar asked Nov 12 '10 02:11

Derek Thurn


2 Answers

Not really. The closest you can get is a void *, but you still need to cast it to an appropriate type before you can use it.

Update:

Trying to build a duck-typed DSL that compiles to C++, basically.

You can go about this in at least two ways:

Union-based variant

struct MyType {
  enum { NUMBER, STRING /* etc */ } type;
  union {
    double number;
    string str;
  };
};

Polymorphic class heirarchy

class MyType {
public:
  /* define pure virtual operations common to all types */
};

class MyNumber : public MyType {
private:
  double number;
public:
  /* implement operations for this type */
};
like image 53
casablanca Avatar answered Sep 20 '22 23:09

casablanca


C#'s dynamic feature is highly dependant on .NET's built-in reflection capabilities. As standard C++ offers next to no reflection support, there's no way you can get a similar behavior. RTTI will allow you to safely downcast pointers but that's pretty much it. You're still quite far to being able to enumerate fields and methods and invoke them dynamically.

like image 34
Trillian Avatar answered Sep 21 '22 23:09

Trillian