lundi 20 avril 2015

Call appropriate constructor function depending on value type

I have a function which fills a container with random values between min and max using uniform distribution.

#include <iostream>
#include <random>
#include <algorithm>
#include <vector>

template<typename TContainer>
void uniform_random(TContainer& container, 
const typename TContainer::value_type min, 
const typename TContainer::value_type max) {
    std::random_device rd;
    std::mt19937 gen(rd());

    // Below line does not work with integers container
    std::uniform_real_distribution<typename TContainer::value_type> distribution(min, max);

    auto lambda_norm_dist = [&](){ return distribution(gen); };
    std::generate(container.begin(), container.end(), lambda_norm_dist);
}

int main() {
    std::vector<float> a(10);
    uniform_random(a,0,10);
    for (auto el : a) { std::cout << el << " "; }
}

Replacing std::vector<float> with std::vector<int> does not work since I would have to use std::uniform_int_distribution instead. Is there a simple and elegant way to pick the right constructor depending on the value_type parameter ?

I was trying so far to use std::numeric_limits<typename TContainer::value_type>::is_integer without success.

Aucun commentaire:

Enregistrer un commentaire