BeeOnRope
BeeOnRope

Reputation: 65046

Idiomatic way of choosing between types based on a compile-time condition

Given an unknown type T, I need something which picks another type R based on the size of T. If T is 8 bytes the type should be pcg64 and if T is 1 to 4 bytes it should be pcg32 and otherwise an error should be produced.

This is what I have:

template <size_t S>
struct pick_pcg_base {
    static_assert(S == 32 || S == 64, "no appropriate pcg for types of this size");
};

template<>
struct pick_pcg_base<32> {
    using type = pcg32;
};

template<>
struct pick_pcg_base<64> {
    using type = pcg64;
};

template <typename T>
struct pick_pcg : public pick_pcg_base<sizeof(T) == 8 ? 64 : (sizeof(T) <= 4 ? 32 : 0)> {};

You would use it like:

template <typename T>
void foo() {
   pick_pcg<T>::type rng;
   ...
}

Is there a more idiomatic way to do it in C++14 with less boilerplate?

Upvotes: 1

Views: 75

Answers (1)

user9400869
user9400869

Reputation:

Extending @Igor Tandetniks' comment:

template<class T>
    struct pick_pcg 
{
    static constexpr size_t S = sizeof(T) == 8 ? 64 : (sizeof(T) <= 4 ? 32 : 0);
    static_assert(S == 32 || S == 64, "no appropriate pcg for types of this size");
    using type = std::conditional<S == 32, pcg32,pcg64>;
};

template<class T>
    using pick_pcg_t = typename pick_pcg<T>::type;

You can now use it like

template <typename T>
void foo() {
   pick_pcg_t<T> rng;
   ...
}

Upvotes: 3

Related Questions