Vincent
Vincent

Reputation: 60421

C++11 type_traits : same type if floating point, double if integral type

I have a type Type and a variable tmp :

template<typename Type> myFunction()
{
    /* SOMETHING */ tmp = 0;
};

I would like to declare tmp as Type if Type is a floating-point type and as double if Type is an integral type. How to do that in C++11 ?

Upvotes: 2

Views: 1099

Answers (2)

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361612

typedef typename std::conditional<
     std::is_floating_point<T>::value, 
     T,                                //if floating, ::type = T
     double                            //else,        ::type = double
>::type value_type;

value_type tmp; //declare variable

I'm assuming T can be only arithmetic type. If you want, you can use std::is_arithmetic to check that first. See other helpful type traits here:

Upvotes: 7

Howard Hinnant
Howard Hinnant

Reputation: 219185

Lookup and use the following traits:

template <bool, class T, class F> struct conditional;
template <class T> struct is_integral;
template <class T> struct is_floating_point;

If that doesn't do it for you, post what you've tried, and the resultant error message.

Upvotes: 4

Related Questions