I am looking for an easy, fast and descriptive way in C++ to check if a value is contained in a fixed set of other values. Like in Python, where one can write
if some_function() in (2, 3, 5, 7, 11):
do_something()
Some obvious options are:
switch/case: If the values in question are integers, then one can write something like this:switch (some_function()) { case 2: case 3: case 5: case 7: case 11: do_something(); }Unfortunately, this only works for integers, and I daresay it's not very pretty.
Use a local variable to keep the temporary result:
const auto x = some_function(); if (x == 2 || x == 3 || x == 5 || x == 7 || x == 11) do_something();I would like to avoid the named temporary variable. Furthermore, this is tedious to write and error-prone.
Use
std::set: This can be written (at least in C++20) as:if (std::set({ 2, 3, 5, 7, 11 }).contains(some_function())) do_something();That's kinda nice, but I fear it has some heavy STL overhead.
Are there other, cheaper methods? Maybe some variadic template solution?