Partial specialization for pointers, c++

允我心安 提交于 2019-12-23 15:10:40

问题


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;
};

回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/4764188/partial-specialization-for-pointers-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!