Check if two types are of the same template

后端 未结 3 605
太阳男子
太阳男子 2020-12-21 16:23

I want to check if two types are of the same template. As an example I want the following snippet of code to return true because both objects are vectors despit

3条回答
  •  春和景丽
    2020-12-21 16:50

    You can but it take a little of metaprog :

    #include 
    #include 
    #include 
    #include 
    
    template  
    struct CheckTypes_impl
    {
        constexpr static bool check (Container1 , Container2 ) { return false; }
    };
    
    template <
        template  class Container1, class...  args1 ,  class...  args2 > 
    struct CheckTypes_impl,Container1>
    {
        constexpr static bool check (Container1 , Container1 ) { return true; }
    };
    
    
    template < 
            template  class Container1,
            class ... args1,
            template  class Container2,
            class ... args2
        > constexpr bool CheckTypes(Container1 c1, Container2 c2)
    {
        return CheckTypes_impl,Container2>::check(c1,c2);
    }
    
    int main()
    {
      std::vector v1(100,0);
      std::vector v2(100,0);
      std::set s;
      std::cout << CheckTypes(v1,v2)  << std::endl;
      std::cout << CheckTypes(v1,s)  << std::endl;
    }
    

    run : https://wandbox.org/permlink/OTuQfl7UBlbxgtCO

    Update : You need " template class Container1, class..." because vector don't take 1 template param, but 2. In the general case you don't know how many default parameters will be used

提交回复
热议问题