khushi-411 / lox.cpp

Lox programming language.
0 stars 0 forks source link

C++ equivalent of Java Object #3

Open khushi-411 opened 8 months ago

khushi-411 commented 8 months ago
  1. C++ generics provides similar functionality. Use templates. Link: https://cplusplus.com/forum/beginner/25721/
  2. Using std::variant. Link: https://shantanugoel.com/2020/04/27/java-object-cpp-std-variant/. More options are:
    • Implemented as:
      using Object = std::variant<std::nullptr_t, std::string, double, bool>;
    • Class objects in Java are superclasses for every class. It's a runtime entity.
    • Use std::conditional
      • Use only when you have two types.
        template <bool B, class T, class F> struct conditional;  // If B = true; select class T else class F
    • Use std::variant
      • Safer version of union.
        template <class... Types> class variant;
    • Use std::any.
      • Need explicit typecasting.
        std::any a = 1;
        std::cout << a.type().name();
        a = 3.14;
        std::cout << a.type().name();
        a = true;
        std::cout << a.type().name();
  3. Stack overflow Link: https://stackoverflow.com/questions/4233123.
    • There is no such equivalent thing in C++, but here are some approaches that can solve the problem:
    • C-style void pointers
      • Anything can be assigned to a void pointer from the new operator as new. It always returns a void pointer but results in a loss of type information about the object pointed at.
    • C-style unions. But here's an important article about why not to use unions: https://www.cppstories.com/2018/06/variant/.
  4. My way: Function overloading

    void Scanner::addToken(TokenType type) {
        Scanner::addToken(type, nullptr);
    }
    
    void Scanner::addToken(TokenType type, std::string literal) {  // todo: Object type
        std::string text = source.substr(start, current);
        tokens.push_back(Token(type, text, literal, line));
    }
    
    void Scanner::addToken(TokenType type, double literal) {        // TODO: object type
        std::string text = source.substr(start, current);
        tokens.push_back(Token(type, text, std::to_string(literal), line));
    }

OTHER WAYS?

khushi-411 commented 8 months ago

More description about std::variant

Ref: https://www.cppstories.com/2018/06/variant/

About variant

How to initialize it?