NoS*_*tAl 3 c++ templates type-traits if-constexpr
我发现许多嵌套的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>())>);
Run Code Online (Sandbox Code Playgroud)
我的问题是:
有没有更好的办法?
编译这种方式比std :: conditional_t慢(假设我需要实例化的类型比我刚才使用内置类型的示例更广泛).
PS这是一个玩具示例,IRCode我会处理一些更复杂的类型.
就个人而言,我觉得这里最明确的方法是"数据驱动".将标准放在表中(写为类模板的特化)并让编译器进行模式匹配以确定类型更短,更不容易出错,更容易阅读或扩展.
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;
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
92 次 |
最近记录: |