简体   繁体   English

我可以在 C++20 的类型别名中使用条件吗?

[英]Can I use condition in type alias in C++20?

As C++ expands to fuse normal computations and type computations I wonder if there is a way to have something like this work?随着 C++ 扩展以融合正常计算和类型计算,我想知道是否有办法让这样的工作?

static const int x = 47;

using T = (x%2) ? int : double;

I know I can use the decltype on a template function that returns the different types based on if constepr, but I wanted something short like my original example.我知道我可以在模板 function 上使用 decltype,该模板根据 if constepr 返回不同的类型,但我想要一些简短的东西,就像我原来的例子一样。

template<auto i> auto determine_type(){
    if constexpr(i%2) {
        return int{};
    } else {
        return double{};
    }
}

note: I am happy to use C++20注意:我很高兴使用 C++20

You can use:您可以使用:

using T = std::conditional_t<(i % 2), int, double>;

For more complex constructions, your approach has too many limitations on the type - would be better to do it this way:对于更复杂的结构,您的方法对类型有太多限制 - 最好这样做:

template<auto i>
constexpr auto determine_type() {
    if constexpr (i%2) {
        return std::type_identity<int>{};
    } else {
        return std::type_identity<double>{};
    }
}

using T = /* no typename necessary */ decltype(determine_type<i>())::type;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 c++20 概念:如何使用可能存在或不存在的类型? - c++20 concepts: How can I use a type that may or may not exist? 如何使用 C++20 std::format? - How can I use C++20 std::format? 我可以在 using 声明中正确使用 C++20 概念吗? - Can I use C++20 concepts properly in a using declaration? 我如何要求(在 C++20 概念中)类型 T 是对浮点类型的引用? - How can I require (in a C++20 concept) that a type T be a reference to a floating point type? 如何将 C++20 约束的多个返回类型要求合并为一个返回类型要求? - How can I combine several return type requirements of C++20 constraints into one return type requirement? 我们可以使用 c++20 的 atomic_ref 并发访问用户类型成员 function 吗? - Can we use c++20's atomic_ref to concurrently accessing user type member function? 当匹配计数大于某个阈值时,我可以使用 C++20 范围来中断吗? - Can I use C++20 ranges to break when matched count is greater than some threshold? 为什么我不能在 c++20 中的 istream_view 之后使用 take() - why I can't use a take() after a istream_view in c++20 如何在 C++20 中使用 std::regular/std::totally_ordered? - How can I use std::regular/std::totally_ordered in C++20? 不能在 C++20 (Visual Studio) 中使用 iostream 作为模块 - Can't use iostream as module in C++20 (Visual Studio)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM