let's say for example I have a function foo() taking a parameter pack Ts. The function however should only accept the parameter pack Ts if there is exactly one type meeting the requirements of std::is_integral. The following code I've written does exactly that as expected.
#include <type_traits>
template <template <typename> typename predicate, typename... Ts>
inline constexpr std::size_t count_if = ((predicate<Ts>::value ? 1 : 0) + ...);
// this method only compiles if exactly one of the given template arguments is of an integral type
template <typename... Ts>
void foo() requires (count_if<std::is_integral, Ts...> == 1) {}
int main()
{
foo<int, double, float>(); //this compiles
//foo<int, long, float>(); //this doesn't, as it should
}
However, let's say the function foo() is being extended by a parameter of template type T like this:
#include <type_traits>
template <template <typename> typename predicate, typename... Ts>
inline constexpr std::size_t count_if = ((predicate<Ts>::value ? 1 : 0) + ...);
// this method only compiles if one of the given template arguments is of an integral type
template <typename T, typename... Ts>
void foo(T) requires (count_if<std::is_integral, Ts...> == 1) {}
int main()
{
foo<double, int, double, float>(double{}); //this compiles
foo<int, int, double, float>(int{}); //this compiles
//foo<double, int, long, float>(double{}); //this doesn't, as it should
}
And now to my question: Is it possible, to make the predicate I'm giving to my count_if function dependent of the template parameter T of my function foo()?
For example, so I could check following:
#include <type_traits>
template <template <typename> typename predicate, typename... Ts>
inline constexpr std::size_t count_if = ((predicate<Ts>::value ? 1 : 0) + ...);
template <typename T, typename... Ts>
void foo(T) requires (count_if<std::is_same<T, ?????> , Ts...> == 1) {}
int main()
{
foo<double, int, double, float>(double{}); //this should compile, as there is exactly one type in parameter pack of type double
foo<int, int, double, float>(int{}); //this should compile, as there is exactly one type in parameter pack of type int
//foo<int, double, float>(); //this shouldn't compile, as there is no int in parameter pack
//foo<double, double, double>(); //this shouldn't compile, as there are two doubles in paramter pack
}
Is this somehow possible? I tried to check it using static_assert() inside the function body, but I can not define a template struct inside it, which I would need so I could write my own predicate like this for example:
template <typename T, typename... Ts>
void foo(T)
{
template <typename U>
struct custom_predicate
{
static constexpr bool value = std::is_same<T, U>::value;
};
static_assert(count_if<custom_predicate, Ts...> == 1);
}
But like I said this isn't possible because I can't define template structs inside a function body.
Does someone have an idea?