A
Art
This is partially an academic question, but I'm trying to understand
templates better. I have a base class that uses template parameters to
define the behavior of its class. I want to subclass this to extend
the behavior. I also want to contain pointers to derived classes
somehow, in a vector, say.
My question is: How do I assign derived classes to the base class?
Here is an example:
template< int INT_TO_HANDLE >
class Base
{
static _HandlesInt( int i )
{
return i == INT_TO_HANDLE;
}
};
class DerivedHandlesOne : public Base< 1 >
{};
class DerivedHandlesTwo : public Base< 2 >
{};
int main()
{
DerivedHandlesOne one;
Base *b = &one; // error: no template params
Base<0> *b0 = &one; // error: cannot conver
Base<1> *b0 = &one; // works! great, but how do I contain
'DerivedHandlesTwo'?
}
I can add a super class to base:
class SuperBase
{
};
template< int FOO >
class Base : public SuperBase
{
static _HandlesInt( int i )
{
return i == FOO;
}
};
class DerivedHandlesOne : public Base< 1 >
{};
class DerivedHandlesTwo : public Base< 2 >
{};
int main()
{
DerivedHandlesOne one;
DerivedHandlesTwo two;
SuperBase *b1 = &one; // works
SuperBase *b2 = &two; // works
}
It turns out that this solves my problem, which is that I have a
'listener' implementation where I need specific handling for each
event, but my question is:
.. Why do I need the superclass for a pointer to the template? Without
any types being visible in the interface isn't it the same,
regardless?
Thanks in advance,
Aaron
templates better. I have a base class that uses template parameters to
define the behavior of its class. I want to subclass this to extend
the behavior. I also want to contain pointers to derived classes
somehow, in a vector, say.
My question is: How do I assign derived classes to the base class?
Here is an example:
template< int INT_TO_HANDLE >
class Base
{
static _HandlesInt( int i )
{
return i == INT_TO_HANDLE;
}
};
class DerivedHandlesOne : public Base< 1 >
{};
class DerivedHandlesTwo : public Base< 2 >
{};
int main()
{
DerivedHandlesOne one;
Base *b = &one; // error: no template params
Base<0> *b0 = &one; // error: cannot conver
Base<1> *b0 = &one; // works! great, but how do I contain
'DerivedHandlesTwo'?
}
I can add a super class to base:
class SuperBase
{
};
template< int FOO >
class Base : public SuperBase
{
static _HandlesInt( int i )
{
return i == FOO;
}
};
class DerivedHandlesOne : public Base< 1 >
{};
class DerivedHandlesTwo : public Base< 2 >
{};
int main()
{
DerivedHandlesOne one;
DerivedHandlesTwo two;
SuperBase *b1 = &one; // works
SuperBase *b2 = &two; // works
}
It turns out that this solves my problem, which is that I have a
'listener' implementation where I need specific handling for each
event, but my question is:
.. Why do I need the superclass for a pointer to the template? Without
any types being visible in the interface isn't it the same,
regardless?
Thanks in advance,
Aaron