Last active
August 29, 2015 14:15
-
-
Save Shekeen/8fa55945d118b9d77db3 to your computer and use it in GitHub Desktop.
Variadic template function for comparison with multiple values
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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