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?
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.
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.
Template in C++is a feature. We write code once and use it for any data type including user defined data types.
"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."
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.
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