指针的部分特化,c ++

Woo*_*ody 4 c++ templates pointers partial-specialization

如何对类GList进行部分特化,以便可以存储I的指针(即I*)?

template <class I>
struct TIList
{
    typedef std::vector <I> Type;
};


template <class I>
class GList
{
      private:
            typename TIList <I>::Type objects;
};
Run Code Online (Sandbox Code Playgroud)

Pet*_*der 7

您不需要专门允许这样做.它可以存储指针.

GList<int*> ints;
Run Code Online (Sandbox Code Playgroud)

无论如何,如果您想将GList专门用于指针,请使用以下语法.

template <class I>
class GList<I*>
{
    ...
};
Run Code Online (Sandbox Code Playgroud)

然后就像I在任何普通模板中一样使用.在上面的示例中GList<int*>,将使用指针特化,并且I将使用int.


Mat*_*sFG 5

上一篇文章指出,您不需要专门针对指针类型,但您可能会这样做.

考虑以下:

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();
}
Run Code Online (Sandbox Code Playgroud)

这不会编译.因为在Foo :: foo中我们有一个指针,我们将它用作变量.

如果添加以下内容,它将使用特化并编译好:

// This is a pointer to T specialization!
template <class T> class Foo<T *> {
    T * t;
public:
    void foo(void)
    {
        t->bar();
    }
};
Run Code Online (Sandbox Code Playgroud)