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?
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?
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.
You can check the types of the values. If they are one of your designated types you can go on, if not you can return the function. See here for more information: http://publib.boulder.ibm.com/infocenter/lnxpcomp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8l.doc%2Flanguage%2Fref%2Fthe_typeid_operator.htm
With the use of typeid you should also be able to throw a compileerror.
Usually whitelisting certain types restricts the usage of templates very much.
Boost has so called concepts which are basically interfaces for templates. instead of whitelisting certain types you can create compile time errors if certain conditions (functions missing, or with wrong arguments etc.) are not met. of course you can also use this to restrict your template arguments to certain types.