Question

In C++, I am trying to implement my own any class using C++. However, before I was able to test it (so if my implementation is bad, feel free to correct me), I got the error: error C2228: left of '.val' must have class/struct/union twice from using the value() function twice, which seems weird when it works everywhere else. The only thing I could think of would be that decltype infront of a function is causing an error, but it shouldn't:

Edit: I have updated the way of changing the variable for the template<class T> any(T V){...} constructor

class any{
protected:
    template<class T> struct variable{
    public:
        T val;
        variable(){}
        variable(T t) : val(t){}
    };
    variable<int> v;
public:
    any(){
        v.val = 0;
    }
    template<class T> any(T V){
        variable<T> nV(V);
        v = nV;
    }
    ~any(){
        delete &v;
    }
    decltype(v.val) value(){ // Error still here
        return v.val;
    }
    template<class T> static any create(T V){
        return any(V);
    }
};
Was it helpful?

Solution

You seem to have a big misunderstanding about this line:

T = NewT;

In C++, the T is a template parameter and therefore it is static during compilation. You can not "set" it as it is not a variable. Unlike some dynamic languages (Python, ...) in C++ types are not objects and can not be modified during runtime. You can instantiate the template with different types (different Ts), but each is like a separate class (called a template class instantiation or class template instantiation, both are equivalent) and it is independent of the other instances.

Since the rest of your design is based on the above false assumption, you run into a lot of problems. The reason that the above line is not showing up as the first error is that it is not even instantiated before other part of the code are compiled (technically: different stages of compilation). That said, you need to understand why the above is impossible in C++ and the rest will follow. You may want to look into other implementations like Boost.Any to get some ideas on how it could be done. (Warning: It's more complicated than your approach)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top