c ++:static assert检查使用的const是否在预定义列表中

时间:2018-05-03 08:57:51

标签: c++ static-assert

如何解决这个问题:

我已经预定了整数的const列表:

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

我想使用static_assert(编译时)来检查是否有其他const值:

#define SOME_IDENTIFIER 1

在列表中。你会怎么做?可能吗?谢谢!

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:2)

而且,在C ++ 11中,具有良好的旧手动部分特化(numbers是全局的简化版本):

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