I would like to define a simple template function which takes a runtime value and determines if it is a member of some set of possible values.
Usage:
int x; // <- pretend this came from elsewhere... if (isoneof(x, {5,3,9,25}) ... Something like:
template <typename T, size_t size> bool isoneof(T value, T (&arr)[size]) { for (size_t i = 0; i < size; ++i) if (value == arr[i]) return true; return false; } I assume that this is doomed to failure, as I don't see how one can create a static array inline.
I can use:
int kPossibilities[] = {5,3,9,25}; if (isoneodf(6, kPossibilities)) ... With a minor change to isoneof:
template <typename T1, typename T2, size_t size> bool isoneof(T1 value, const T2 (&arr)[size]) { for (size_t i = 0; i < size; ++i) if (value == arr[i]) return true; return false; } Which also makes it a tad more flexible.
Does anyone have an improvement to offer? A better way to define a "set of static values inline"?