Last active
April 19, 2022 06:08
-
-
Save saxbophone/8398ed06f6955ffdbbc59b6e812fbb46 to your computer and use it in GitHub Desktop.
Variadic xor template function --takes any types convertible to bool
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 <cstddef> | |
namespace { | |
/* | |
* Helper function, variadic xor | |
* It works by counting the number of true values and returning true only | |
* if this number is 1. | |
*/ | |
template <typename T> | |
constexpr std::size_t only_one_helper(T t) { | |
return (bool)t; | |
} | |
template <typename T, typename... Args> | |
constexpr std::size_t only_one_helper(T t, Args... args) { // recursive variadic function | |
return only_one_helper(t) + only_one_helper(args...); | |
} | |
template <typename T, typename... Args> | |
constexpr bool only_one(T t, Args... args) { // recursive variadic function | |
return only_one_helper(t, args...) == 1; | |
} | |
} | |
int main() { | |
return only_one(false, true, true) or only_one(true, false, true, false); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment