Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

template class restriction

Tags:

c++

templates

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
}
like image 214
Ali1S232 Avatar asked Apr 21 '11 23:04

Ali1S232


People also ask

Can template be used for class?

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.

What is a template template parameter in C++?

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.

What is the difference between Typename and class in template?

There is no difference between using <typename T> OR <class T> ; i.e. it is a convention used by C++ programmers.

How do I restrict a template type in C++?

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.


1 Answers

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.

like image 62
James McNellis Avatar answered Sep 29 '22 17:09

James McNellis