I'm trying to conditionally add types to a tuple template type based on some compile time condition, as follows:
template <typename T>
class Base { ... }
template <int I>
class Derived : public Base<std::tuple<std::conditional<I % 8 == 0, int, void>::type,
std::conditional<I % 4 == 0, double, void>::type,
std::conditional<I % 2 == 0, float, void>::type>>
{ ... }
I understand that this isn't valid code, but conceptually I'm trying to conditionally add types to the tuple's list. I would like the type to be skipped when the conditional resolves to void
.
Is there a way to do something like this?
A small part of your question does not compute:
std::conditional<I % 1 == 0, float, void>:
Since the remainder of any integer when divided by 1 is 0, this conditional will always be true.
Whatever the actual intent was here, I'll just give an example with two conditionals that can be trivially extended to include additional conditionals, as needed:
#include <tuple>
#include <functional>
template <typename T>
class Base {};
template <int I>
class Derived : public Base<
decltype(std::tuple_cat(
std::declval<
std::conditional_t<I % 4 == 0,
std::tuple<int>,
std::tuple<>>>(),
std::declval<
std::conditional_t<I % 2 == 0,
std::tuple<float>,
std::tuple<>>>()
))>
{
};
Derived<4> a;
Base<std::tuple<int, float>> &b=a;
Derived<2> c;
Base<std::tuple<float>> &d=c;
This is taking advantage of the fact that std::tuple_cat
is perfectly happy with std::tuple<>
, and we just need to (ab)use it to glue the right combination of tuples together.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With