Search code examples
c++templatesoperator-overloadingassignment-operator

c++ left hand assignment operator


i have a class (wich should hold any value) like this:

class Value
{

    public:

        Value();
        Value(const Value& value);
        virtual ~Value();
        void operator= (const Value& value);

        template<class T>
        void operator= (T value);
...
}

now my question:

why can't i implement an assignment operator for this class like this:

template<class T>
void operator=(T& value, const Value& v)
{...}

I wan to desing a class wich works the following:

Value v;

v = 'c';
v = 13;
v = 5.6;
int i = 5;
v = &i;

int y = v;
char b = v;

i want to put any datatype into it and out of it. at the moment this works fine for:

v = 'c';
v = 13;
v = 5.6;

but not for:

int y = v;

what works is:

int y = v.get<int>();

but this is not as nice as

int y = v;

would be


Solution

  • You can easily fix the compilation error by adding template type cast to your class like following:

    class Value
    {
    ...
            template <class T> operator T();
    };
    
    Value va;
    int i = va;
    

    I still believe you will find the task of implementing 'boost::any' yourself quite challenging, but why not? :)