Search code examples
c++interpreterdynamic-languagesdynamic-typing

Storing elements of different type in a vector/array in C++?


I'm trying to create a simple dynamic language interpreter in C++. I'd like to be able to declare dynamically typed arrays, but I'm not sure how to store them in some object in C++.

In Ruby/Python I can store anything I want, but what's an efficient way of doing this in C++?

(Also, if someone has a link to a simple open source lexer/parser/interpreter for dynamic languages like Ruby, I'd appreciate a link).


Solution

  • You will have to roll some custom solution based on your language's semantics. For example, you can use boost::any to store any object, but you won't be able to perform, for example, name lookups. A knowledge of some assembler is useful here because you're basically emulating that. What most people do is something like

    struct Object {
        boost::any cppobject;
        std::unordered_map<std::string, std::function<void(boost::any&, std::vector<boost::any>&)> funcs;
    };
    
    std::vector<Object> stuff;
    

    When, in your hypothetical language, you have something like

    stuff[0].hi();
    

    Then you can convert it into something like

    std::vector<boost::any> args;
    // fill args
    stuff.at(0).funcs["hi"](stuff.at(0).cppobject, args);
    // now args holds the result
    

    It's quite possible to optimize this scheme further, but not to generalize it further, as it's already maximally general.