Template Class Constraint

I am wondering if there is any way to restrict the creation of code for the template using custom conditions in my case, I want the function foo to be called only if the template class T was inherited by the class of the class (something like this)

template <class T:public bar> void foo() { // do something } 
+6
source share
2 answers

You can limit T , but using "Substitution error is not an error" (SFINAE):

 template <typename T> typename std::enable_if<std::is_base_of<bar, T>::value>::type foo() { } 

If T not derived from bar , the specialization of the function template will fail and will not be taken into account when resolving overloads. std::enable_if and std::is_base_of are the new components of the C ++ standard library added to the upcoming revision, C ++ 0x. If your compiler / standard library implementation does not yet support them, you can also find them in C ++ TR1 or Boost.TypeTraits.

+9
source

Yes, you can use the following technique (for public inheritance). This will cause the overhead of only one pointer initialization.

Edit : overwrite

 template<typename Parent, typename Child> struct IsParentChild { static Parent* Check (Child *p) { return p; } Parent* (*t_)(Child*); IsParentChild() : t_(&Check) {} // function instantiation only }; template<typename T> void foo () { IsParentChild<Bar, T> check; // ... } 
0
source

Source: https://habr.com/ru/post/886433/


All Articles