J
John Harrison
Daniel said:Hi all!
I'm getting some for me "unexpected behaviour" from g++ 4.1.2 when
compiling this simple test program:
#include <cstdlib>
#include <cstdio>
using namespace std;
template<typename t>
class MyTemplate
{
public:
inline void operator=(const t& val)
{
printf("%d\n", (int)val);
}
};
class MyClass : public MyTemplate<short>
{};
int main()
{
MyClass abc;
abc=5;
//((MyTemplate<short>&)abc)=5;
return EXIT_SUCCESS;
}
It complains that operator= is not defined for MyClass -- however, to my
understanding of C++, it should be inhertied like a simple function?
The program works as expected when I either replace abc=5; with the line
commented out below or when I replace operator= by a simple function like
inline void foo(const t& val)
and
abc.foo(5);
Are operators handled differently from ordinary functions when
inheriting or maybe when inheriting from templates?
The problem is that operator= is defined automatically for each class.
So the auto-generated operator= for MyClass is hiding the operator= in
MyTemplate.
You would see exactly the same behaviour with foo
template<typename t>
class MyTemplate
{
public:
void foo(const t& val);
};
class MyClass : public MyTemplate<short>
{
void foo(const MyClass&);
};
int main()
{
MyClass abc;
abc.foo(5); // cannot convert 5 to MyClass
}
You might be able to get round this with a using declaration
class MyClass : public MyTemplate<short>
{
public:
using MyTemplate<short>:
};
Haven't tested that though.