'What is struct Cleaner <T*> mean?

What is struct Cleaner <T*> mean? Is it specific the second Cleaner can only accept the type of pointer? what is the terminology of this usage in C++?

template <typename T> struct Cleaner {
   static void clean ( T x ) { 
   }
};

template <typename T> struct Cleaner<T*> {
   static void clean ( T* x ) {
      if ( x ) { delete x; } 
   }
};

template <typename T> void release ( T x ) { Cleaner<T>::clean ( x ); }


Solution 1:[1]

The idea is to provide two behaviours for the function release() depending on the type of its argument (pointer or not).

We could also have written two overloads

template <typename T> void release2(T) { }
template <typename T> void release2(T *x) { delete x; }

In your example, the distinction is done on two versions of the Cleaner helper type (partial specialisation, as stated in the comment) but the idea is the same.

In C++17 we could also written a more concise version

#include <trait_types>

template <typename T> void release3(T x) {
    if constexpr (std::is_pointer<T>::value) {
        delete x;
    }
}

When it comes to the usage

int
main()
{
  int i=12;
  int *pi=new int(23);
  release3(i);  // NO delete
  release3(pi); // delete is used
  return 0;
}

Note that the null check before delete is not necessary (it's done internally, as with free() in C).

Solution 2:[2]

First, you defined a class template named Cleaner.

Second, you "partially specialized" the class template for T*, so that if T is a pointer type, it will create the specialized version of "clean()".

In this case, at compile-time, if T is a pointer type, the Cleaner<> template will use the second patter, while if T is a fully qualified type, it will use the original.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 prog-fh
Solution 2 N. Prone