In Java you can restrict generics so that the parameter type is only a subclass of a particular class. This allows the generics to know the available functions on the type.
I haven't seen this in C++ with templates. So is there a way to restrict the template type and if not, how does the intellisense know which methods are available for <typename T>
and whether your passed-in type will work for the templated function?
As of C++11, there is no way to constrain template type arguments. You can, however, make use of SFINAE to ensure that a template is only instantiated for particular types. See the examples for std::enable_if
. You will want to use it with std::is_base_of
.
To enable a function for particular derived classes, for example, you could do:
template <class T>
typename std::enable_if<std::is_base_of<Base, T>::value, ReturnType>::type
foo(T t)
{
// ...
}
The C++ working group (in particular, Study Group 8) are currently attempting to add concepts and constraints to the language. This would allow you to specify requirements for a template type argument. See the latest Concepts Lite proposal. As Casey mentioned in a comment, Concepts Lite will be released as a Technical Specification around the same time as C++14.
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