许多嵌套std :: conditional_t的替代品?

问题描述 投票:2回答:2

我发现许多嵌套的std :: conditional_t难以阅读,所以我选择了一个不同的模式(在自动返回类型的函数上调用decltype):

template<bool is_signed, std::size_t has_sizeof>
auto find_int_type(){
    static_assert(sizeof(int)==4);
    if constexpr(is_signed){
        if constexpr(has_sizeof==4){
            return int{};
        } else if constexpr (has_sizeof==8){
            return std::int64_t{};
        } else {
            return;
        }
    } else {
        if constexpr(has_sizeof==4){
            return (unsigned int){};
        }
        else if constexpr (has_sizeof==8){
            return std::uint64_t{};
        } else {
            return;
        }
    } 
}

static_assert(std::is_same_v<int, decltype(find_int_type<true, 4>())>);
static_assert(std::is_same_v<unsigned int, decltype(find_int_type<false, 4>())>);
static_assert(std::is_same_v<void, decltype(find_int_type<false, 3>())>);
static_assert(std::is_same_v<void, decltype(find_int_type<false, 5>())>);
static_assert(std::is_same_v<std::int64_t, decltype(find_int_type<true, 8>())>);
static_assert(std::is_same_v<std::uint64_t, decltype(find_int_type<false, 8>())>);
static_assert(std::is_same_v<void, decltype(find_int_type<false, 9>())>);

我的问题是:

有没有更好的办法?

编译这种方式比std :: conditional_t慢(假设我需要实例化的类型比我刚使用内置类型的示例更广泛)。

附:这是一个玩具示例,IRCode我会处理一些更复杂的类型。

c++ templates typetraits if-constexpr
2个回答
6
投票

就个人而言,我觉得这里最明确的方法是“数据驱动”。将标准放在表中(写为类模板的特化)并让编译器进行模式匹配以确定类型更短,更不容易出错,更容易阅读或扩展。

template<bool is_signed, std::size_t has_sizeof>
struct find_int_type_impl { using type = void; }; // Default case

template<> struct find_int_type_impl<true,  4> { using type = std::int32_t;  };
template<> struct find_int_type_impl<true,  8> { using type = std::int64_t;  };
template<> struct find_int_type_impl<false, 4> { using type = std::uint32_t; };
template<> struct find_int_type_impl<false, 8> { using type = std::uint64_t; };

template<bool is_signed, std::size_t has_sizeof>
using find_int_type = typename find_int_type_impl<is_signed, has_sizeof>::type;

1
投票

由于std::disjunction<Args...>继承自Args... valuetrue中的第一种类型,或者如果没有这种类型存在,Args...中的最后一种类型,我们可以(ab)使用它来产生一个多路分支:

template<class... Args>
using select = typename std::disjunction<Args...>::type;

template<bool V, class T>
struct when {
    static constexpr bool value = V;
    using type = T;
};

template<bool is_signed, std::size_t has_sizeof>
using find_int_type = select<
    when<is_signed, select<
        when<has_sizeof==4, int>,
        when<has_sizeof==8, std::int64_t>,
        when<false, void>
    >>,
    when<!is_signed, select<
        when<has_sizeof==4, unsigned int>,
        when<has_sizeof==8, std::uint64_t>,
        when<false, void>
    >>
>;
© www.soinside.com 2019 - 2024. All rights reserved.