Since there is a restriction on allowed non-type variadic templates, I am trying to write a function taking an arbitrary number of doubles using enable_if
. In essen
Here is a generic approach – a TMP for binary folding, using C++14. First, let's define the basic combining operations:
#include
struct and_op
{
using type = bool;
using identity = std::true_type;
template static constexpr bool value = A && B;
};
struct or_op
{
using type = bool;
using identity = std::false_type;
template static constexpr bool value = A || B;
};
Now the actual fold
mechanic:
template
struct fold;
template
struct fold : Op::identity {};
template
struct fold
: std::integral_constant {};
template
struct fold
: std::integral_constant::value>> {};
Next, we need a way to create unary traits from binary traits by binding:
template class BPred, typename T>
struct bind_pred
{
template
struct pred_1st : std::integral_constant::value> {};
template
struct pred_2nd : std::integral_constant::value> {};
};
Finally, a helper wrapper to combine the result of applying a unary predicate:
template class UPred, typename ...Args>
struct fold_pred : fold::value...> {};
That's it. Now let's get to work:
template
using maybe_double = bind_pred::pred_2nd;
#include
#include
int main()
{
std::cout
<< std::boolalpha
<< fold_pred::value << '\n'
<< fold_pred::value << '\n';
}
In C++17 (or C++1z, rather), you can write direct solutions with less code thanks to the new fold expressions. For example:
template class UPred, typename ...Args>
static constexpr bool pred_all = (UPred::value && ...);
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^ unary fold
Usage:
static_assert(pred_all);