Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading