I'm trying to move some code to templates using the new decltype
keyword, but when used with dereferenced pointers, it produces reference type. SSCCE:
#include <iostream>
int main() {
int a = 42;
int *p = &a;
std::cout << std::numeric_limits<decltype(a)>::max() << '\n';
std::cout << std::numeric_limits<decltype(*p)>::max() << '\n';
}
The first numeric_limits
works, but the second throws a value-initialization of reference type 'int&'
compile error. How do I get a value type from a pointer to that type?
You can use std::remove_reference
to make it a non-reference type:
std::numeric_limits<
std::remove_reference<decltype(*p)>::type
>::max();
Live demo
or:
std::numeric_limits<
std::remove_reference_t<decltype(*p)>
>::max();
for something slightly less verbose.
If you are going from a pointer to the pointed-to type, why bother dereferencing it at all? Just, well, remove the pointer:
std::cout << std::numeric_limits<std::remove_pointer_t<decltype(p)>>::max() << '\n';
// or std::remove_pointer<decltype(p)>::type pre-C++14
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With