Search code examples
c++compile-timestatic-assert

Is it possible to use boost::mpl::contains on a static vector_c?


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.


Solution

  • 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");