【问题标题】:Is it possible to use boost::mpl::contains on a static vector_c?是否可以在静态 vector_c 上使用 boost::mpl::contains?
【发布时间】:2016-04-07 19:52:05
【问题描述】:

我正在为this question 寻找一个不那么笨拙的答案,即在编译时检查模板参数是否在数字列表中。我不仅想检查函数的范围,还想在编译时检查整数是否在任意整数列表中。该答案的作者写道:“当 C++0x 使用 constexpr、static_assert 和用户定义的文字时,事情会变得容易得多”,但我不知道 确切如何。

我想使用this boost::mpl::contains 函数(或其他任何名称),但它只需要一个类型作为第二个参数。

【问题讨论】:

  • vector_c 也将保存类型。不清楚你在问什么。
  • 这个问题与您是否可以在containsvector_c 的问题有什么关系?问题只是:你如何在这样的序列上使用contains
  • 抱歉用词不当。我想要做的是在编译时检查模板参数是否在数字列表中。

标签: c++ compile-time static-assert


【解决方案1】:

只是为了好玩:

template <int first, int... last>
struct int_list {
    static bool constexpr check(int c) {
      return first == c ? true : int_list<last...>::check(c);
    }
};

template <int first>
struct int_list<first> {
    static bool constexpr check(int c) { return c == first; }
};

using my_sequence = int_list<1, 5, 12, 45, 76, 60>;

static_assert(my_sequence::check(10), "No tenner");

【讨论】:

  • @user4581301,虽然不同:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多