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

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

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

+5
source share
3 answers

A way to do this is to use it std::enable_ifin some form or form. The supported type selector is then used as the return type. For instance:

  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;
  }

, , , is_supported. std::enable_if ++ 2011, boost, .

, , . .

+8

Usually a whitelist of certain types greatly restricts the use of templates.

Boost has so-called concepts , which are mainly interfaces for templates. instead of whitelisting certain types, you can create compile-time errors if certain conditions (functions are missing or with incorrect arguments, etc.) are not satisfied. Of course, you can also use this to restrict your template arguments to certain types.

0
source

All Articles