简体   繁体   中英

Getting a typename given the typename of a pointer to it in C++

Consider the following code:

class c {
  //...
};

template <typename T>
void f(T k)
{
    auto item = new T;
    //...
}

We declare a class c and a template function f that creates a new object type T .

I want to change this function f so the template parameter can be a pointer type , it will be used as follows:

auto ptr = new c;
f<c*>(ptr);

Now, the problem comes when I try to create a new item auto item = new T; , because now T is now the typename of a pointer to c .

I know T will always be a pointer to something, how can I get the typename being pointed to by T ? I want to do something like:

template <typename T>
void f(T k)
{
    // If T = int* -> Q = int
    typename ??????? Q;    // <<<<<<<<
    auto item = new Q;
    //...
}

With std::remove_pointer :

#include <type_traits>

using Q = typename std::remove_pointer<T>::type;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM