How to make partial specialization of the class GList so that it is possible 开发者_运维技巧to store pointers of I (i.e I*) ?
template <class I>
struct TIList
{
typedef std::vector <I> Type;
};
template <class I>
class GList
{
private:
typename TIList <I>::Type objects;
};
You don't need to specialise to allow that. It can store pointers already.
GList<int*> ints;
Anyway, if you wanted to specialise GList for pointers, use the following syntax.
template <class I>
class GList<I*>
{
...
};
Then just use I
as you would in any normal template. In the example above with GList<int*>
, the pointer specialisation would be used, and I
would be int
.
Previous post states that you don't NEED to specialize for pointer types, but you might.
Consider the following:
struct Bar {
void bar(void) { /* do work */ }
};
template <class T> struct Foo {
T t;
void foo(void)
{
t.bar(); // If T is a pointer, we should have used operator -> right?
}
};
int main(int argc, char * argv[])
{
Foo<Bar *> t;
t.foo();
}
This won't compile. Because in Foo::foo we have a pointer yet we use it as variable.
If you add the following, it will use the specialization and compile fine:
// This is a pointer to T specialization!
template <class T> class Foo<T *> {
T * t;
public:
void foo(void)
{
t->bar();
}
};
精彩评论