Search code examples
c++dynamicc++11dynamic-typing

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?


Solution

  • 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 */
    };