Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

float or double type depend on size of pointer

Tags:

c++

I want to declare a struct where one of my type is either float or double depending on pointer size.

#if size of pointer is 4
# define Real float
#else
# define Real double
#endif 
struct mydata {
 //...
 Real speed;
 //... 
};
#undefine Real

without using macro?

like image 396
Imla Assuom Avatar asked Dec 23 '22 20:12

Imla Assuom


1 Answers

You can use std::conditional (or conditional_t) to choose a type based on a compile-time condition:

#include <type_traits>

using Real = std::conditional_t<sizeof(void*) == 4, float, double>;

If you use C++11 but not C++14, you'd need:

using Real = std::conditional<sizeof(void*) == 4, float, double>::type;
like image 192
interjay Avatar answered Dec 25 '22 22:12

interjay