Search code examples
c++c++11decltype

Is it possible to obtain a type from decltype?


decltype returns a full type of an expression/entity. Is it possible to get only type?

For example, is it possible to make p to have type T in this case?

class T;
T t;
const T& tt = t;
decltype(tt) p; //decltype makes this const T& too as same as tt

Solution

  • It depends on entirely on what you want to do in the cases of cv T* and cv T[N]. If in all of those cases you just want T, then you'll need to write a type trait:

    template <typename T>
    struct tag { using type = T; };
    
    template <typename T>
    struct just_t
    : std::conditional_t<std::is_same<std::remove_cv_t<T>,T>::value,
                         tag<T>,
                         just_t<std::remove_cv_t<T>>>
    { };                   
    
    template <typename T>
    struct just_t<T*> : just_t<T> { };
    
    template <typename T>
    struct just_t<T&> : just_t<T> { };
    
    template <typename T, size_t N>
    struct just_t<T[N]> : just_t<T> { };
    
    template <typename T>
    struct just_t<T[]> : just_t<T> { };
    

    If you're okay with pointers staying as they are and arrays decaying into pointers, then simply:

    template <typename T>
    using just_t = std::decay_t<T>;