Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we define a template function for some data types only? [duplicate]

Tags:

c++

templates

Possible Duplicate:
C++ templates that accept only certain types

For example, if we want to define a template function which we can use integers, floats, doubles but not strings. Is there an easy way to do so?

like image 627
derekhh Avatar asked Dec 29 '11 18:12

derekhh


People also ask

How will you restrict the template for a specific datatype?

There are ways to restrict the types you can use inside a template you write by using specific typedefs inside your template. This will ensure that the compilation of the template specialisation for a type that does not include that particular typedef will fail, so you can selectively support/not support certain types.

How function template is defined?

Function templates are similar to class templates but define a family of functions. With function templates, you can specify a set of functions that are based on the same code but act on different types or classes.

Can templates be used for user defined data types?

Template in C++is a feature. We write code once and use it for any data type including user defined data types.

What are the differences between function template and template function?

"A function template is a template that is used to generate functions. A template function is a function that is produced by a template. For example, swap(T&, T&) is a function tem-plate, but the call swap(m, n) generates the actual template function that is invoked by the call."


1 Answers

The way to do this to use std::enable_if in some shape or form. The selector for the supported type is then used as the return type. For example:

  template <typename T> struct is_supported { enum { value = false }; };
  template <> struct is_supported<int> { enum { value = true }; };
  template <> struct is_supported<float> { enum { value = true }; };
  template <> struct is_supported<double> { enum { value = true }; };

  template <typename T>
  typename std::enable_if<is_supported<T>::value, T>::type
  restricted_template(T const& value) {
    return value;
  }

Obviously, you want to give the traits a better name than is_supported. std::enable_if is part of C++2011 but it is easily implemented or obtained from boost in case it isn't available with the standard library you are using.

In general, it is often unnecessary to impose explicit restrictions as the template implementation typically has implicit restrictions. However, sometimes it is helpful to disable or enable certain types.

like image 65
Dietmar Kühl Avatar answered Oct 24 '22 20:10

Dietmar Kühl