How to use a condition to check if typename T is an integer type of type float in C ++

I am going to write a template for generating a random data vector. The problem in std::uniform_int_distributionaccepts only the integer type std::uniform_real_distributionfor the float type. I want to combine both. Here is my code.

#include <vector>
#include <random>
#include <algorithm>
#include <iterator>
#include <functional>

template<typename T>
std::vector<T> generate_vector(size_t N, T lower = T(0), T higher = T(99)) {
    // Specify the engine and distribution. 
    if constexpr (std::is_integral<T>) {
    std::uniform_int_distribution<T> distribution(lower, higher);
    }
    else if constexpr (std::is_floating_point<T>) {
    std::uniform_real_distribution<T> distribution(lower, higher);
    }
    std::mt19937 engine; // Mersenne twister MT19937
    auto generator = std::bind(distribution, engine);
    std::vector<T> vec(N);
    std::generate(vec.begin(), vec.end(), generator);
    return vec;

I am confused how to implement instructions in an if condition. Integer type should include: short, int, long, long long, unsigned short, unsigned int, unsigned long, or unsigned long long. Float type includes float, double, or long double.

Any suggestion of help?

+6
source share
2 answers

In the pre-C ++ 17 compiler, you can use specialized specialization to implement logic if- else.

// Declare a class template
template <bool is_integral, typename T> struct uniform_distribution_selector;

// Specialize for true
template <typename T> struct uniform_distribution_selector<true, T>
{
   using type = typename std::uniform_int_distribution<T>;
};

// Specialize for false
template <typename T> struct uniform_distribution_selector<false, T>
{
   using type = typename std::uniform_real_distribution<T>;
};


template<typename T>
std::vector<T> generate_vector(size_t N, T lower = T(0), T higher = T(99))
{
   // Select the appropriate distribution type.
   using uniform_distribution_type = typename uniform_distribution_selector<std::is_integral<T>::value, T>::type;

   uniform_distribution_type distribution(lower, higher);
   std::mt19937 engine;
   auto generator = std::bind(distribution, engine);
   std::vector<T> vec(N);
   std::generate(vec.begin(), vec.end(), generator);
   return vec;
}
+6
source

, if constexpr :

#include <type_traits>

if constexpr (std::is_integral_v<T>) {  // constexpr only necessary on first statement
    ...
} else if (std::is_floating_point_v<T>) {  // automatically constexpr
    ...
}

++ 17. . ++ :

if constexpr ( ++ 17)

<type_traits> ( ++ 11)

constexpr specifier ( ++ 11)

Constant Expressions .

+4

All Articles