template and operator =

Hi,

I've a problem with my template class and I don't understand why.

I've this base class template

template <typename T> class TBase
{
public:

TBase & operator=(T val) {m_Val = val; return *this;}

private:

T m_Val;
}

class CClassFLOAT : public TBase<float>
{

}

In my main function, i expected to do something like that :

void main()
{
CClassFLOAT f;

f=1.0f;
}

But Visual Studio 2005 fails to compile it with the following error :
error C2679: binary '=' : no operator found which takes a right-hand operand of type 'float' (or there is no acceptable conversion)

Is someone able to say me what i'm doing wrong ?



Last edited on
1 ) You are missing semicolons after the class bodies
2 ) You are using void main instead of int main
3 ) You didn't define the = operator for CClassFLOAT, if CClassFLOAT won't have any difference to TBase<float>, you can declare it as typedef: typedef TBase<float> CClassFLOAT;
Yes, this is because operator overloading and inheritance don't mesh seamlessly.

The method you are trying to call is CClassFLOAT& CClassFLOAT::operator=( float ), but
the method you've defined is (effectively) TBase& operator=( float ).

You are asking the compiler to perform an implicit downcast of a TBase& to a CClassFLOAT&.
Unfortunately you can't do that. You will need to move operator= to the derived type.

Thanks for the answer ...
@Bazzy, sorry, the syntax errors are just bad copy/paste

@jsmith
Thanks i better understand the situation and the problème due to the downcasting.

But if my operation = returns a void ... this downcasting issue should disapear and it should work ... but it doesn't :(

I've changed my template as this ...

template <typename T> class TBase
{
public:

void operator=(T val) {m_Val = val;}

private:

T m_Val;
};

But i get the same error ?

The assignment operator really should return something so that it works like assignment
of POD-types. Namely, this wouldn't work with your class:

1
2
CClassFLOAT f, g;
f = g = 1.0;  // Compile error; the expression g = 1.0 returns void, which cannot be assigned to f. 


You should bite the bullet and overload operator= in the derived class (you can have it call the
base class implementation).
Topic archived. No new replies allowed.