c++ - std::is_same equivalent for unspecialised template types -


in 1 project have found possibility stay dry lot of code except small parts stay same template specialisations of template. here small working example i'm doing check templated class i'm using:

template<typename t> class a{};  template<typename t> class b{};  template<template<class> class c> void do_stuff() {     if(std::is_same<a<int>,c<int>>::value)     {     // stuff     } else if(std::is_same<b<int>,c<int>>::value)     // stuff b     } }  int main() {     do_stuff<a>(); } 

what instead using

std::is_same<a,c>::value 

to determine template type. there function me or missing pattern work better in case?

i see like

template<template<class> class c, typename t> void do_stuff();  do_stuff<a,t>(); 

but seems wrong way me.

you write is_same_template trait partially specialized when 2 template template parameters same:

template <template <typename...> class, template<typename...> class>  struct is_same_template : std::false_type{};  template <template <typename...> class t> struct is_same_template<t,t> : std::true_type{}; 

then can write is_same_template<a,c>::value.

note won't work templates have non-type template parameters, std::array.

some compilers not consider alias template equivalent template aliases, following result in std::false_type:

template <typename t, typename alloc> using myvec = std::vector<t, alloc>;  is_same_template<std::vector, myvec>; 

this considered defect in standard, shouldn't rely on behaviour until fix implemented in common compilers.


that said, need careful put in if branches, code needs compile regardless of template instantiated with. in c++17 you'll able use if constexpr solve problem, you'll need tag dispatch or have different specializations if branches have code valid a or b.

template <template <typename...> class> struct tag{};  template <template <typename> class t> void do_stuff() {     do_stuff(tag<t>{}); }  void do_stuff(tag<a>) {     std::cout << "a"; }  void do_stuff(tag<b>) {     std::cout << "b";    } 

Comments

Popular posts from this blog

magento2 - Magento 2 admin grid add filter to collection -

Android volley - avoid multiple requests of the same kind to the server? -

Combining PHP Registration and Login into one class with multiple functions in one PHP file -