I have run into a very strange error today and was wondering if anyone else has seen this. Some digging on google suggests it might be a compiler error. I've seen this on VS2008 and GCC 4.1.2. I was able to build a test harness to repro the issue. It is below:
#include class Cloneable
{
public:
template TYPE* clone() const { return dynamic_cast< TYPE* > ( clone() ); }
virtual Cloneable* clone() const = 0;
};
// simple template class that defines an interface
// for cloning objects.
class X : public Cloneable
{
public:
X(int _y ) : data(_y) { }
virtual ~X() { /* DO NOTHING */ }
virtual Cloneable* clone() const { return new X(data); }
protected:
X() { /* DO NOTHING */ }
int data;
};
class Y : public X
{
public:
Y(double f, int y) : X(y), dataf(f) { /* DO NOTHING */ }
virtual ~Y() { /* DO NOTHING */ }
virtual Cloneable\* clone() const { return new Y(dataf, data); }
protected:
double dataf;
};
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
int main(int argc, char* argv[])
{
X* x = new X(1);
X* x1 = x->clone();
Y\* y = new Y(2.12, 4);
Y\* y1 = y->clone();
delete y;
delete y1;
delete x;
delete x1;
return 0;
}
The clone fails in both cases in the main function. It should cast properly. There seem to be two ways to fix this. If i move the templated function from Cloneable to X & Y it works in both cases. The other is to use clone() in the main function and dyna cast there. A standard C cast in the templated function also doesn't work. Its like the compiler is erroneously changing the protection level on the function and then gets confused and just dumps out the error.
1>Compiling...
1>main.cpp
1>.\main.cpp(40) : error C2275: 'X' : illegal use of this type as an expression
1> .\main.cpp(12) : see declaration of 'X'
1>.\main.cpp(40) : error C2059: syntax error : ')'
1>.\main.cpp(43) : error C2275: 'Y' : illegal use of this type as an expression
1> .\main.cpp(24) : see declaration of 'Y'
1>.\main.cpp(43) : error C2059: syntax error : ')'
Anyone seen this work in a different compiler or know of a workaround to make it compile (aside from the ones I mentioned)? -- Joseph Dempsey Sr. Software Engineer joseph_r_dempsey@yahoo.com
modified on Friday, November 5, 2010 2:18 PM