Skip to content

Instantly share code, notes, and snippets.

@saxbophone
Last active April 19, 2022 06:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save saxbophone/8398ed06f6955ffdbbc59b6e812fbb46 to your computer and use it in GitHub Desktop.
Save saxbophone/8398ed06f6955ffdbbc59b6e812fbb46 to your computer and use it in GitHub Desktop.
Variadic xor template function --takes any types convertible to bool
#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