Home How to use condition to check if typename T is integer type of float type in C++
Reply: 0

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

user7215 Published in September 19, 2018, 3:28 am

I am going to write a template to generate a vector of random data. The problem is std::uniform_int_distribution only accepts integer type, and std::uniform_real_distribution for 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 confusing how to implement statements within if conditions. 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 help suggestion?

share|improve this question
  • 4
    if constexpr and std::is_integral and std::is_floating_point – Justin Jan 11 at 4:38
  • Thank you Justin, I just tried, and found it is C++ 17 supported. – ted930511 Jan 11 at 5:18

2 Answers 2

active oldest votes
up vote 7 down vote accepted
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.293366 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO