【问题标题】:Can I use condition in type alias in C++20?我可以在 C++20 的类型别名中使用条件吗?
【发布时间】:2020-07-25 09:07:36
【问题描述】:

随着 C++ 扩展到融合普通计算和类型计算,我想知道是否有办法让这样的工作?

static const int x = 47;

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

我知道我可以在一个基于 if constepr 返回不同类型的模板函数上使用 decltype,但我想要一些简短的东西,就像我原来的例子一样。

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

注意:我很高兴使用 C++20

【问题讨论】:

  • 这样的用例是什么?还是只是好奇?
  • std::conditional?它已经存在了一段时间
  • @Rakete1111 主要是对语言限制的好奇。

标签: c++ template-meta-programming constexpr c++20


【解决方案1】:

你可以使用:

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

对于更复杂的结构,您的方法对类型有太多限制 - 最好这样做:

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;

【讨论】:

  • 自 C++11 以来就一直存在。
  • 有什么限制?默认 ctor、移动/复制 ctor 的要求?
  • @NoSenseEtAl 默认可初始化、可返回、可能衰减。
猜你喜欢
  • 1970-01-01
  • 2017-02-26
  • 1970-01-01
  • 2020-05-26
  • 2021-04-13
  • 2022-10-09
  • 1970-01-01
  • 2020-01-14
  • 1970-01-01
相关资源
最近更新 更多