开发者

Partial specialization for pointers, c++

开发者 https://www.devze.com 2023-02-05 20:49 出处:网络
How to make partial specialization of the class GList so that it is possible 开发者_运维技巧to store pointers of I (i.e I*) ?

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();
    }
};
0

精彩评论

暂无评论...
验证码 换一张
取 消