I want:
template<class ... T>
auto foo()
{
// ✨ magic ✨
}
Such that:
(foo<int, char, bool>() == foo<char, int, bool>()) // True
(foo<int>() == foo<char>()) // False
In other words, I want foo to return a unique id for the combination of types passed to it rather than the permutation of types passed to it.
My first idea was that there might be some way to sort the parameter pack at compile time, though I'm not sure how exactly that would work.
My current solution is this:
// Precondition: Client must pass the parameters in alphabetical order to ensure the same result each time
template<class ... T>
std::type_index foo()
{
return std::make_type_index(typeid(std::tuple<T ... >));
}
The problem with this is that it doesn't work if the client is using type aliases. For example:
using my_type = char;
(foo<bool, int, my_type>() == foo<bool, char, int>()) // False
One idea I had is to assign a new prime number as an id for every new type that the function handles. Then I could assign a unique id for a particular combination of types by multiplying their prime number ids together. For example:
id of int = 2
id of bool = 3
id of char = 5
id of <int, bool, char> = 2 * 3 * 5 = 30
id of <bool, int, char> = 3 * 2 * 5 = 30
Only problem is how I'm going to assign unique prime number ids to each type without incurring a runtime penalty.
std::set<std::type_index>{typeid(T)...}std::type_indexis the only way to sort arbitrary types, and it isn'tconstexpr. If the set of possible types is limited, you can try putting them all in astd::tuplethen sort the types according to their position in that tuple.std::map<std::type_index, std::size_t>to either look up or generate the unique prime number ids of each type. But theoretically, you can hard code the prime number id of each type that you use, so then there would be no runtime penalty.foo<type1>()and foo<type2, type3>()` and I would expect them to return unique values no matter what types are chosen.