C++ 为非变异算法定义constexpr值集的最佳方法

C++ 为非变异算法定义constexpr值集的最佳方法,c++,templates,boost,constexpr,C++,Templates,Boost,Constexpr,我想对编译时已知的一组值使用中的非变异算法和boost-range算法。我想知道哪种方法最有效(在性能和内存方面),不包括开关盒方法 让我们考虑EnUM(类或非)的一些值。< /P> enum Enum { One, Two, Three }; 让我们考虑微不足道的函数布尔OISONERONE2(EnUM)。 使用方法,我知道它可以用两种方式编写: 1. 标准::初始值设定项列表 然后,可以通过以下方式实现功能: bool isOneOrTwo(Enum e) { c

我想对编译时已知的一组值使用
中的非变异算法和boost-range算法。我想知道哪种方法最有效(在性能和内存方面),不包括开关盒方法

让我们考虑EnUM(类或非)的一些值。< /P>

enum Enum
{
   One,
   Two,
   Three
};

让我们考虑微不足道的函数<代码>布尔OISONERONE2(EnUM)。 使用

方法,我知道它可以用两种方式编写: 1. <代码>标准::初始值设定项列表

然后,可以通过以下方式实现功能:

bool isOneOrTwo(Enum e)
{
    constexpr auto oneAndTwo = make_array(One, Two);
    return std::any_of(std::begin(oneAndTwo),
                       std::end(oneAndTwo),
                       [e](auto i){return e == i;});
}
哪一个更好(
std::initializer\u list
std::array
)或者有其他方法更快/更便宜


如果我将
std::any_of(begin_it,end_it,lambda)
更改为
boost::algorithm::any_of_equal(make_iterator_range(begin_it,end_it),value)
,它会有什么影响吗?

我认为您可能已经将问题减少得太多了。你能描述一下你试图解决的真正问题吗,否则
e!=三个
将是我的解决方案。如果您经常测试连续值的范围,您可能还想提供一种方法来生成类似于从
中获得的代码(e>=min&&e
enum
只是一个简单的示例,它可以设置为
constepr
struct
,只需
运算符==()
、非连续枚举等。您是否尝试过#1?一个非空的
std::initializer\u列表
永远不能是
constepr
。在C++17中,您可以编写
constepr auto One和Two=std::array{One,Two};
来使用类模板推断,而不需要
生成数组
template<typename... T>
constexpr auto make_array(T&&... args)
{
    return std::array<typename std::common_type<T...>::type, sizeof...(T)>{{std::forward<T>(args)...}};
}
bool isOneOrTwo(Enum e)
{
    constexpr auto oneAndTwo = make_array(One, Two);
    return std::any_of(std::begin(oneAndTwo),
                       std::end(oneAndTwo),
                       [e](auto i){return e == i;});
}