79076847

Date: 2024-10-11 05:02:11
Score: 1.5
Natty:
Report link

After more than 10 years of this question, I was looking for some C++ code equivalent to the Java code in the question.

As I could not find any, I ended up doing my own version as close as possible to the original Java but in C++17.

Note1: I was not considering performance, etc.

Note2: Yes, you need to know ahead the types you are going to use (using variants=etc), but that is in the Java code as well, right?

#include <iostream>
#include <variant>
#include <vector>

template <typename T>
class GenericAttribute {
private:
    T m_value;

public:

    GenericAttribute(T value) {
        setValue(value);
    }

    T getValue() {
        return m_value;
    }

    void setValue(T value) {
        m_value = value;
    }
};

class Custom {
public:
    Custom() {}

    std::string toString() const {
        return "My custom object";
    }
};

static std::ostream& operator<<(std::ostream& os, const Custom& obj) {
    return os << obj.toString();
}

int main() {
    using variants = std::variant<
        GenericAttribute<int>*,
        GenericAttribute<double>*,
        GenericAttribute<Custom>*
    >;

    std::vector<variants> attributes = {};
    attributes.push_back(new GenericAttribute<int>(1));
    attributes.push_back(new GenericAttribute<double>(3.1415926535));
    attributes.push_back(new GenericAttribute<Custom>(Custom{}));

    for (auto& attr : attributes) {

        std::visit([](auto& object) {
            std::cout << object->getValue() << std::endl;
        }, attr);
    }

    return 0;
}
Reasons:
  • Long answer (-1):
  • Has code block (-0.5):
  • Ends in question mark (2):
  • Low reputation (1):
Posted by: fbussolin