Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++: static assert checking whether used const is in predefined list

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!

like image 275
user3691223 Avatar asked May 03 '18 08:05

user3691223


2 Answers

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

like image 156
Vittorio Romeo Avatar answered Oct 22 '22 09:10

Vittorio Romeo


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);
like image 2
Daniel Langr Avatar answered Oct 22 '22 10:10

Daniel Langr