QVM: Quaternions, Vectors, Matrices

SFINAE/enable_if

SFINAE stands for Substitution Failure Is Not An Error. This refers to a situation in C++ where an invalid substitution of template parameters (including when those parameters are deduced implicitly as a result of an unqualified call) is not in itself an error.

In absence of concepts support, SFINAE can be used to disable function template overloads that would otherwise present a signature that is too generic. More formally, this is supported by the Boost enable_if library.

For example, Boost QVM defines operator* overload which works with any user-defined matrix and vector types. The naive approach would be to declare this overload as follows:

Even if the function definition might contain code that would compile only for Matrix and Vector types, because the function declaration itself is valid, it will participate in overload rezolutions when multiplying objects of any two types whatsoever. This typically renders overload resolutions ambiguous and the compiler (correctly) issues an error.

Using enable_if, Boost QVM declares such overloads in a way that they retain their generic signature but only participate (in overload resolutions) if the passed parameters make sense depending on the semantics of the operation being defined:

For brevity, function declarations throughout this documentation specify the condition which controls whether they are enabled or not without specifying exactly what enable_if construct is used to achieve this effect.