Re: Class hierarchy generated from a template
Dimitar wrote:
What is wrong with the following:
template<size_t size> class X;
template<>
class X<0> {};
template<>
class X<1>
{
public:
void M(const char (&x)[1]) {}
};
template<size_t size>
class X : public X<size - 1>
{
public:
void M(const char (&x)[size]) {}
};
Sample use would be:
char arr[3] = "ab";
X<4> x;
x.M(arr);
However this does not compile with MS VC7. If arr has size 4 then it
compiles.
Am I trying to do something that is not possible - for example the line
"class X : public X<size - 1>"? If this is not valid I would expect
that it should not compile at all then (have not had chance to test
with gcc) or at least give some warning.
And No, I can not use vector, or string, or anything more inteligent
than C-array (there are reasons why, but they are not related to the
question in this post)
I revised the code so that it compiles as expected. Note in addition to
the "using" directive, I replaced the size_t non-type template
parameter with an "int". Otherwise, it would be necessary to append a
"u" to each integral constant value used to instantiate the class
template - a requirement which is both non-obvious and almost certainly
completely unnecessary since the template cannot be instantiated with a
negative value anyway.
template<int size> class X;
template<>
class X<0> {};
template<>
class X<1>
{
public:
void M(const char (&x)[1]) const
{
}
};
template<int size>
class X : public X<size-1>
{
public:
using X<size-1>::M;
void M(const char (&x)[size]) const
{
}
};
int main()
{
const char arr[3] = "ab";
X<10> x;
x.M(arr);
}
Greg
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]