Please ask about problems and questions regarding this tutorial on answers.ros.org. Don't forget to include in your question the link to this page, the versions of your OS & ROS, and also add appropriate tags. |
Enable If
Description: An if operator for template type arguments.Keywords: ecl mpl
Tutorial Level: INTERMEDIATE
Contents
Usage
These allow you to various compile tricks with SFINAE (Substitution Failure Is Not An Error). One usage case is to eliminate template instantiations for any type you do not wish to explicitly support.
1 // This will instantiate if it is anything except float or double.
2 template <typename T, typename Enable = void>
3 class TestObject {
4 public:
5 bool isFloatSpecialisation() { return false; }
6 };
7
8 // This specialisation will instantiate it T is float or double.
9 template <typename T>
10 class TestObject< T, typename enable_if< is_float<T> >::type > {
11 public:
12 bool isFloatSpecialisation() { return true; }
13 };
Reporting Errors at Compile Time
FailedObject is a simple class that guarantees a compile time failure if an attempt to instantiate it is made (private constructor). This is useful in tandem with the if function to report bad instantiations.
For example, the parent template definition above could be instead: