How to get type of type pointer?

I have a pointer like Ptr. It can be T *, unique_ptr, shared_ptr or others. How to get its pointed type at compile time? I try the following but failed

template<class Ptr>
void f()
{
    typedef decltype(*Ptr()) T; // give unexpected results
}

The following remote answer works very well.

typedef typename std::remove_reference<decltype(*std::declval<Ptr>())>::type T;
+4
source share
2 answers

I was in the middle of writing this answer when I saw that someone else had already posted it, so I gave up. But then this other answer disappeared, so here it is. If the original appears again, I will delete it.

If Ptr(for example) int*, then it decltype(*Ptr())is evaluated as int&, and not int, which is probably the cause of your error (no matter what it is). Try:

std::remove_reference<decltype(*Ptr())>::type

, , Ptr :

std::remove_reference<decltype(*std::declval<Ptr>())>::type

+3

.

.

template <typename T> Pointer;

template <typename T> Pointer<T*>
{
   typedef T Type;
};

template <typename T> Pointer<shared_ptr<T>>
{
   typedef T Type;
};

template <typename T> Pointer<unique_ptr<T>>
{
   typedef T Type;
};

template<class Ptr>
void f()
{
    typedef typename Pointer<Ptr>::Type PointerType;
}
+12

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


All Articles