Skip to content

any_of<c1, …, c2>(v)

This simple C++17 template implements constexpr any_of for matching a value against a list of constants.

/** type_of_list<...>::type - helper structure for determining type of the first item in the list */
template<auto ... List> struct type_of_list;
template<auto List> struct type_of_list<List> { using type = decltype(List); };
template<auto First, auto ... List > struct type_of_list<First, List...> : type_of_list<First> {};

/** type_of<...>::type - determines type of the first item in the list */
template<auto ... List>
using type_of = typename type_of_list<List...>::type;

/** any_of<...>(value) - compares value against all template parameters and returns true if any matches */
template<auto ... List>
inline constexpr bool any_of(type_of<List...> value) noexcept {
	return ((value == List) || ...);
}

Also available on github as a gist any_of.hpp

Usage

#include <iostream>
#include <string>

enum class num { zero, one, two };

int main() {
    num v { num::one };
    std::cout << any_of<num::zero, num::two>(v) << " " << any_of<num::zero, num::one>(v) << std::endl;
}

This example is also available on https://www.onlinegdb.com/BJLvFo7PN

Post a Comment

Your email is never published nor shared. Required fields are marked *
*
*

*