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!
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
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With