Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what does the < > beside the struct do?

Tags:

c++

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.

like image 429
Mox Avatar asked Feb 06 '23 16:02

Mox


1 Answers

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.

like image 137
463035818_is_not_a_number Avatar answered Feb 08 '23 15:02

463035818_is_not_a_number