2

When compiling the following:

template <class T>
class Number
{
    private:
        T num;
    public:
        Number() {}
        Number( T n ) : num(n) {}
        operator T() const { return num; }
};

int main()
{
    Number<int> n=5;
    Number<char> c=4;
    int i;

    c=int(5);
    i=n;
    c=n;

    return 0;
}

The compiler gets stuck at the third assignment saying there is no match for operator= in c=n. Shouldn't n get converted to int, which in turn will be assigned to c?

Baruch
  • 20,590
  • 28
  • 126
  • 201

2 Answers2

4

According to the standard, at most one user-defined conversion (constructor or conversion function) is implicitly applied to a single value. Here, you are expecting the compiler to apply the constructor for Number<char> and the conversion operator for Number<int>. See: https://stackoverflow.com/a/867804/677131.

Community
  • 1
  • 1
Lubo Antonov
  • 2,301
  • 14
  • 18
2

That's because there is no int operator when your templated class is constructed with the templated type as char.

You actually don't have an assigment operator here, only a constructor and a type operator. This means your compiler would likely have put in a default one probably along the lines of:

Number<T>& operator=( Number<T>& rhs );

You should implement your own assignment operator, this should fix your problem. A generic solution could be as follows, but relies on a valid assignment between the types.

template <typename T, typename V>
class Number
{
    private:
        T num;
    public:
        Number() {}
        Number( T n ) : num(n) {}
        operator T() const { return num; }
        operator=( V& rhs ){ num = rhs; // etc }
};

You also need to make your class constructor explicit to avoid implicit conversion (unless that is what you want).

Konrad
  • 39,751
  • 32
  • 78
  • 114
  • `templated class is constructed as a char` - I have big problems trying to figure out what you mean there. A class that is constructed _as a_ `char`? – sehe Apr 02 '12 at 11:40
  • `n` is constructed as an `int`. It has an `int` operator. `c` can be assigned `int`s. BTW, it doesn't work the other way either, so the problem is not trying to assign `int` to `char`. – Baruch Apr 02 '12 at 11:42
  • Can you please clarify? I don't understand what the problem is. – Baruch Apr 02 '12 at 11:45