如何在编译时从一些不同的类型中选择类型?

das*_*fex 2 c++ metaprogramming c++11 c++14

我想做这样的事情:

template <uint64_t N>
struct a {
  static constexpr T1 v1 = {};
  static constexpr T2 v2 = {};
  static constexpr auto v3 = (N % 2 == 1 ? v1 : v2);
};
Run Code Online (Sandbox Code Playgroud)

但是我不能将 (? :) 用于不同类型。我怎么能做到这一点?

Evg*_*Evg 6

例如,您可以使用if constexprlambda 函数 (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;
    }();
};
Run Code Online (Sandbox Code Playgroud)

另一个解决方案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));
};
Run Code Online (Sandbox Code Playgroud)

  • 非常好的 `std::get()` 解决方案:也适用于 C++11/C++14。 (3认同)