Mox Mox - 23 days ago 8
C++ Question

what does the < > beside the struct do?

Ok the following code is copied from another stackoverflow question
here

template<typename T>
struct remove_pointer
{
typedef T type;
};

template<typename T>
struct remove_pointer<T*>
{
typedef typename remove_pointer<T>::type type;
};


While I do understand that this is a recursive definition in template, what puzzled me are the lines

template<typename T>
struct remove_pointer<T*>


does that mean remove_pointer will result in T=int*? Why wouldn't T=int**? explanation is appreciated.

Answer

This is a specialization for pointer types. Specializations may also have template parameters. So this template's type is just T in the general case but, if T is a pointer type, then its type is T with the pointer removed. Maybe it is more clear when giving the parameter a different name:

template<typename T>
struct remove_pointer
{
    typedef T type;
};

template<typename S>
struct remove_pointer<S*>       // specialization for T = S*
{
    typedef typename remove_pointer<S>::type type;
};

i.e. in the general case type is just T, but if T is a pointer, then the template is instantiated for S, where T == S*.

PS: I think the special thing about this example is that the specialization introduces a new template parameter. A "normal" specialization would look like this:

template<>
struct remove_pointer<int*>   // specialization for T = int*
{
    typedef typename remove_pointer<int>::type type;
};

However, this isnt very useful, as we want it to work for any type. The solution is to introduce an additional template parameter on the specialization (S). Afaik this additional parameter has to be deducible from the parameters to the original template, in this case S can be deduced, because S is just T without the pointer.