-1

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

Naibaf
  • 111
  • 8
  • Is that a typo in your question? Did you mean `void operator=`? – melpomene Oct 02 '15 at 14:13
  • 1
    See [Overloading assignment operator in a class template that can cast to another template type](http://stackoverflow.com/questions/8305952/overloading-assignment-operator-in-a-class-template-that-can-cast-to-another-tem). – agold Oct 02 '15 at 14:15
  • Why would you want to implement it like this? What problem do you believe it would help you solve? – Igor Tandetnik Oct 02 '15 at 14:24
  • Just call the function `assign` instead of `operator=` and all will be good. If not, then you have a much more serious design problem anyway. – Christian Hackl Oct 02 '15 at 14:27
  • yes sorry it is a typo. i will correct it – Naibaf Oct 02 '15 at 14:27
  • BTW , it's expected that `operator=` will return a reference to `*this`, so its signature should be `Value& operator=(T)`. – Toby Speight Oct 02 '15 at 14:30
  • 1
    Look into Boost::Any or Boost::Variant unless you're just doing this for fun. – AndyG Oct 02 '15 at 14:52

3 Answers3

0

Because the standard says that an assignment operator must be a member function with only one parameter.

13.5.3$1 Assignment [over.ass]:

An assignment operator shall be implemented by a non-static member function with exactly one parameter.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
0

You can implement a typecast operator like this

operator int()
{
    if(current_value_is_not_int)
        throw MyException("Current value is not int");

    //return int value
}
Thomas Sparber
  • 2,827
  • 2
  • 18
  • 34
0

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? :)

SergeyA
  • 61,605
  • 5
  • 78
  • 137