2

I wonder if I can do some conditional typing based on if a template parameter is a pointer or not?

So for instance I want the get method below to return T itself if it is a pointer(i.e. T*). Or T* if is not a pointer (i.e. T).

template<typename T>
class MyContainer {
    T get(); // If T is a pointer
    T* get(); // If T is not a pointer
}
einstein
  • 13,389
  • 27
  • 80
  • 110
  • 1
    how about `std::remove_pointer_t * get();` – M.M Jul 14 '19 at 08:17
  • @MichaelChourdakis it is almost the same, but it doesn't help me that much. I think it is basing the overload resolution based on the parameter. My `get()` method doesn't have any parameters. – einstein Jul 14 '19 at 08:21
  • `I think it is basing the overload resolution based on the parameter.` - no, it is not. – KamilCuk Jul 14 '19 at 08:24
  • @MichaelChourdakis you are right it was probably a duplicate. – einstein Jul 14 '19 at 09:53

1 Answers1

2

Just condition if it's a pointer and if not:

#include <type_traits>

template<typename T>
class MyContainer {
    std::conditional_t<std::is_pointer<T>::value, T, T*> get();
};
KamilCuk
  • 120,984
  • 8
  • 59
  • 111