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 inherieted by class bar(something like this)
template <class T:public bar> void foo()
{
// do something
}
A class template can be declared without being defined by using an elaborated type specifier. For example: template<class L, class T> class Key; This reserves the name as a class template name.
In C++ this can be achieved using template parameters. A template parameter is a special kind of parameter that can be used to pass a type as argument: just like regular function parameters can be used to pass values to a function, template parameters allow to pass also types to a function.
There is no difference between using <typename T> OR <class T> ; i.e. it is a convention used by C++ programmers.
For example, if we want to constrain some math functions to only take floating point types, we can use is_floating_point : template <typename T, typename = typename std::enable_if_t< std::is_floating_point<T>::value>> class Vector2{ public: Vector2(T x, T y) : x(x), y(y) {}; T dot(Vector2<T> v) { return x * v.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With