Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restricting templates to only certain classes?

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?

like image 890
user997112 Avatar asked Dec 18 '13 22:12

user997112


1 Answers

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.

like image 176
Joseph Mansfield Avatar answered Sep 20 '22 10:09

Joseph Mansfield