Search code examples
c++c++11type-traits

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 ?


Solution

  • 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: