7

how to solved this issue:

I have predefinded const list of integers:

const auto numbers = {1, 5, 10};

I want to use static_assert (compilation time) to check whether some other const value:

#define SOME_IDENTIFIER 1

is in the list. How would you do that? Is it possible? Thank you!

5
  • const int numbers = {1, 5, 10}; this line itself is incorrect Commented May 3, 2018 at 9:00
  • typo const int numbers[] = {1, 5, 10}; Commented May 3, 2018 at 9:01
  • Which language standard should be used here? Commented May 3, 2018 at 9:02
  • 1
    Off-topic: prefer a constexpr to a macro. Had to say it, and I'll be going now. Commented May 3, 2018 at 9:07
  • Fixed the typo. Couldn't resist. Sorry. Also forces C++11 and greater. Commented May 3, 2018 at 9:08

2 Answers 2

8

C++2a:

constexpr std::array numbers{1, 5, 10};

constexpr int some_id = 1;
static_assert(std::any_of(numbers.begin(), numbers.end(), 
    [](const auto& x){ return x == some_id; }));

C++17:

template <typename C, typename X>
constexpr bool contains(const C& container, const X& x)
{
    for(const auto& elem : container) if(x == elem) return true;
    return false;
}

constexpr std::array numbers{1, 5, 10};

constexpr int some_id = 1;
static_assert(contains(numbers, some_id));

live example on wandbox.org


C++14:

constexpr int numbers[]{1, 5, 10};

constexpr int some_id = 1;
static_assert(contains(numbers, some_id));

live example on wandbox.org


C++11:

template <typename T>
constexpr bool contains_impl(std::size_t n, const T* arr, const T& x)
{
    return n != 0 && (arr[0] == x || contains_impl(n - 1, arr + 1, x));
}

template <typename T, std::size_t N>
constexpr bool contains(const T(&arr)[N], const T& x)
{
    return contains_impl<T>(N, &arr[0], x);
}

live example on wandbox.org

Sign up to request clarification or add additional context in comments.

4 Comments

Unfortunately, any_of isn't constexpr until C++20. Not that it's hard to write one's own constexpr contains or something.
@chris: fixed! :)
@VittorioRomeo - In record time, no less :P
C++11 version has infinite recursion if the element is not found.
2

And, in C++11 with good old manual partial specialization (simplified version where numbers are global):

constexpr std::array<int,3> numbers = {1, 5, 10};

template <size_t I,int N>
struct check {
   static constexpr bool value = 
      (numbers[I] == N) || check<I-1,N>::value;
};

template <int N>
struct check<0,N> {
   static constexpr bool value = (numbers[0] == N);
};

constexpr int n = 1;
static_assert(check<numbers.size()-1,n>::value);

1 Comment

I added a C++11 solution as well :) - BTW I don't think array::operator[] is constexpr in C++11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.