1

I am searching for a less klunky answer to this question, namely check at compile time whether a template parameter is in a list of numbers. I would like to not just check the range of a function, but check whether the integer is in an arbitrary list of integers at compile time. The author of that answer wrote that "Things will be much easier when C++0x is out with constexpr, static_assert and user defined literals," but I don't see exactly how.

I thought to use this boost::mpl::contains function (or whatever it's called), but it only takes a type as a second parameter.

Community
  • 1
  • 1
nimble_ninja
  • 323
  • 1
  • 13
  • `vector_c` will hold types as well. Unclear what you are asking. – SergeyA Apr 07 '16 at 19:54
  • What does that question have to do with the question of whether or not you can `contains` on a `vector_c`? Is the question just: how do you use `contains` on such a sequence? – Barry Apr 07 '16 at 20:23
  • Sorry for the poor choice of words. What I want to do is check at compile time whether a template parameter is in a list of numbers. – nimble_ninja Apr 07 '16 at 20:55

1 Answers1

2

Just for the fun of it:

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");
SergeyA
  • 61,605
  • 5
  • 78
  • 137