基于编译时条件在类型之间进行选择的惯用方式

时间:2019-05-06 01:50:41

标签: c++ templates c++14

鉴于未知类型T,我需要一些东西来根据R的大小选择另一种类型T。如果T是8个字节,则类型应该是pcg64,如果T是1到4个字节,则类型应该是pcg32,否则将产生错误。

这就是我所拥有的:

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)> {};

您将以如下方式使用它:

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

在C ++ 14中,是否有一种更惯用的方式以更少的样板实现呢?

1 个答案:

答案 0 :(得分:3)

扩展@Igor Tandetniks的评论:

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;

您现在可以像使用它

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