Re: g++ and subclass template specialization
On 4/9/07 4:42 PM, in article
1176162168.342204.25260@l77g2000hsb.googlegroups.com, "vilarneto@gmail.com"
<vilarneto@gmail.com> wrote:
Today I started to use template specializations in a project and
suddenly faced a curious problem. Following is a complete example
that shows the situation:
class A {
};
template<class T>
class B : public A {
};
template<>
class B<int> {
};
int main(int argc, char *argv[]) {
A *a;
a = new B<double>;
a = new B<int>;
return 0;
}
g++ 3.4.6, refuses to compile the 2nd assignment, issuing a "cannot
convert `B<int>*' to `A*' in assignment" error. However, under my
concepts B is a subclass of A (as expected, the compiler accepts the
1st assignment).
B<double> is a subclass of A - but due to the specialization, B<int> is not
a subclass of anything. To declare B<int> as a subclass of A, the
specialization for B<int> needs to be changed to this:
template <>
class B<int> : public A
{
};
In other words, B<int> is its own class template - and shares nothing with
the general B class template. So, if you want B<int> to have any of the same
base classes or members as the general B class template, you will have to be
sure that the B<int> specialization makes the same set of declarations as
the general template - otherwise, they will not be present in the B<int>
specialization.
Is this a compiler bug or a language specification? Does anyone
suggests a portable workaround (other than avoid TS and subclass
B<int> as a nontemplate class C)?
Declare B<int> exactly how you want B<int> to be declared - or move whatever
implementation that is to be shared with the general template into a common
(non-template) base class.
C++ is really an interesting language... after 10+ years of daily
use, sometimes we find ourselves amused with something unexpected.
I'm a bit surprised that after 10 years of C++, you would not have known how
class template specializations work.
Greg