Checking if two template parameter packs are same

I have a class template that has a parameter pack and that class template has a member function template which also have a parameter pack. Now inside that member function template, I need to know whether the two template parameter packs are same(meaning they have same length as well as all of their corresponding elements are same).


template<typename... T>
struct C
{
    template<typename... U>
    void f()
    {
        //how can I know here if the two template packs are same(meaning of same length as well as have same elements in the same order)
        bool result = /*what to write here?*/
        std::cout << "T... and U... are: " << (result? "same":"not same")<<"\n";
    }
};
int main()
{
    C<int, int, int, int> c;
    c.f<int,int, int, int>(); // same

    c.f<int, int, int>();     //not same
   
    c.f<int, int, int, double>(); //not same

    c.f<int, double>();           //not same
}

As you can see I don’t know what should come at the right hand side of bool result = ?;. Maybe a trait can be created to do.

>Solution :

Below is shown one way of doing this using fold expressions and SFINAE:

template<typename... T> struct Helper{};
template <typename... T, typename...U> 
std::enable_if_t<sizeof...(T)==sizeof...(U), bool> is_all_same(Helper<T...>, Helper<U...>) 
{
    return (... && std::is_same_v<Helper<T>,Helper<U>>); 
    
}; 
template <typename... T, typename...U> 
std::enable_if_t<!(sizeof...(T)==sizeof...(U)), bool> is_all_same(Helper<T...>, Helper<U...>) 
{
    return false;
} 

Then you can just write:

bool result = is_all_same(Helper<T...>{}, Helper<U...>{});

Working demo

Leave a Reply