I\'m wondering if there is any way to restrict generating code for a template using custom conditions in my case i want to function foo to be called only if template class T has
Yes, following technique can be used (for public inheritance). It will cause an overhead of just one pointer initialization.
Edit: Re-writing
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;
// ...
}
You can restrict T
though using "Substitution Failure Is Not An Error" (SFINAE):
template <typename T>
typename std::enable_if<std::is_base_of<bar, T>::value>::type foo()
{
}
If T
is not derived from bar
, specialization of the function template will fail and it will not be considered during overload resolution. std::enable_if
and std::is_base_of
are new components of the C++ Standard Library added in the forthcoming revision, C++0x. If your compiler/Standard Library implementation don't yet support them, you can also find them in C++ TR1 or Boost.TypeTraits.