Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert a reference type to a value type?

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?

like image 412
ScumCoder Avatar asked Nov 29 '22 07:11

ScumCoder


2 Answers

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.

like image 144
Shoe Avatar answered Dec 10 '22 02:12

Shoe


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
like image 29
T.C. Avatar answered Dec 10 '22 04:12

T.C.