Search code examples
c++decltype

How do you get the datatype from a pointer to a datatype with decltype?


The decltype operator when used with a type* retutns type&. is there a way to get just the type.

int* i;
decltype(*i) l; // int& l;

int o; // decltype(???) o;

I just wanted to know if there is a way to do tht, do I need a library or something like that?

edit:

I originally didn't want to use any libraries but I would if i have to and I did try to find other questions to fix the problem but didn't find any that helped. I'm sorry I didn't properly mention that.


Solution

  • Your use of decltype is not just some id-expression in the operator, so the usual rules of decltype apply:

    • If decltype is applied to an lvalue, the type is T&. (Your case)
    • If decltype is applied to an xvalue, the type is T&&.
    • If decltype is applied to a prvalue, the type is T.

    See also What is decltype and how is it used?

    How you approach this problem is up to you, and depends on the specific situation. Here are some options:

    • std::remove_pointer_t<decltype(i)>
    • std::remove_reference_t<decltype(*i)>
    • decltype(auto(*i)) (C++23)