Skip to content

Instantly share code, notes, and snippets.

@Shekeen
Last active August 29, 2015 14:15
Show Gist options
  • Save Shekeen/8fa55945d118b9d77db3 to your computer and use it in GitHub Desktop.
Save Shekeen/8fa55945d118b9d77db3 to your computer and use it in GitHub Desktop.
Variadic template function for comparison with multiple values
#include <iostream>
#include <cstdarg>
//IsOneOf(x, a, b, c) is an equivalent of (x == a || x == b || x == c)
template<typename T>
bool IsOneOf(const T& var, const T& val)
{
return var == val;
}
template<typename T, typename... Args>
bool IsOneOf(const T& var, const T& val, const Args&... vals)
{
return IsOneOf(var, val) || IsOneOf(var, vals...);
}
int main()
{
std::cout << IsOneOf(1, 0, 1, 2, 3) << std::endl; // 1
std::cout << IsOneOf('a', 'd', 'e', 'f') << std::endl; // 0
// std::cout << IsOneOf(true, 1, 0) << std::endl; <-- Compilation error: deduced conflicting types ('bool' vs 'int')
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment