robert badea writes:
> Hello!
> I was messing around with C++ and wanted to do a type_trait which would
> return true if a type is one of the given types.
>
> Do you have any idea how can i improve the design ?
Something like the following. The odd "<= 0" comparison, instead of "> 0"
was needed because ">" gets parsed …differently in the context of a template
parameter.
To check if the given type occurs exactly once, just change that to "!= 1".
#include <utility>
#include <type_traits>
#include <iostream>
template<typename T, typename ...Types>
struct count_occurences {
static constexpr int how_many=((std::is_same_v<T, Types> ? 1:0) + ...);
};
template<typename T, typename first_type, typename ...Types>
using occurs_in=std::conditional_t<
count_occurences<T, first_type, Types...>::how_many <= 0,
std::false_type, std::type_type>;
int main()
{
std::cout << occurs_in<int, float, int, double, int>::value
<< std::endl;
std::cout << occurs_in<int, double>::value << std::endl;
return 0;
}