Partial specialization for pointers, C ++

How to make a partial specialization of the GList class so that pointers to i (i.e., i *) can be stored?

template <class I> struct TIList { typedef std::vector <I> Type; }; template <class I> class GList { private: typename TIList <I>::Type objects; }; 
+4
source share
2 answers

You do not need to specialize in this. It can store pointers already.

 GList<int*> ints; 

In any case, if you want to specialize GList for pointers, use the following syntax.

 template <class I> class GList<I*> { ... }; 

Then just use I , as in any regular template. In the above example with GList<int*> , pointer specialization will be used, and I will be int .

+7
source

The previous post states that you DO NOT need to specialize in pointer types, but you can.

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 will not compile. Since in Foo :: foo we have a pointer, but we use it as a variable.

If you add the following, it will use specialization and compile the fine:

 // This is a pointer to T specialization! template <class T> class Foo<T *> { T * t; public: void foo(void) { t->bar(); } }; 
+5
source

Source: https://habr.com/ru/post/1336527/


All Articles