我想做这样的事情:

template <uint64_t N>
struct a {
  static constexpr T1 v1 = {};
  static constexpr T2 v2 = {};
  static constexpr auto v3 = (N % 2 == 1 ? v1 : v2);
};
但是我不能将(?:)与其他类型一起使用。我该怎么做?

最佳答案

例如,您可以使用if constexpr和lambda函数(C++ 17):

template <std::uint64_t N>
struct a {
  static constexpr T1 v1 = {};
  static constexpr T2 v2 = {};
  static constexpr auto v3 =
    [] {
        if constexpr (N % 2 == 1)
            return v1;
        else
            return v2;
    }();
};
带有std::tuple(C++ 14)的另一种解决方案:
template <std::uint64_t N>
struct a {
  static constexpr T1 v1 = {};
  static constexpr T2 v2 = {};
  static constexpr auto v3 = std::get<N % 2>(std::make_tuple(v2, v1));
};

关于c++ - 如何在编译时从一些不同的类型中选择类型?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/63646394/

10-11 23:23
查看更多