Reference documentation for deal.II version 9.1.0-pre
List of all members
constraint_and_return_value< true, T > Struct Template Reference

#include <deal.II/base/template_constraints.h>

Detailed Description

template<typename T>
struct constraint_and_return_value< true, T >

This specialization of the general template for the case of a true first template argument declares a local alias type to the second template argument. It is used in order to construct constraints on template arguments in template (and member template) functions. The negative specialization is missing.

Here's how the trick works, called SFINAE (substitution failure is not an error): The C++ standard prescribes that a template function is only considered in a call, if all parts of its signature can be instantiated with the template parameter replaced by the respective types/values in this particular call. Example:

template <typename T>
typename T::type foo(T)
{
...
};
...
foo(1);

The compiler should detect that in this call, the template parameter T must be identified with the type "int". However, the return type T::type does not exist. The trick now is that this is not considered an error: this template is simply not considered, the compiler keeps on looking for another possible function foo.

The idea is then to make the return type un-instantiatable if certain constraints on the template types are not satisfied:

template <bool, typename>
struct constraint_and_return_value;
template <typename T>
struct constraint_and_return_value<true,T>
{
using type = T;
};

constraint_and_return_value<false,T> is not defined. Given something like

template <typename>
struct int_or_double
{
static const bool value = false;
};
template <>
struct int_or_double<int>
{
static const bool value = true;
};
template <>
struct int_or_double<double>
{
static const bool value = true;
};

we can write a template

template <typename T>
typename constraint_and_return_value<int_or_double<T>::value,void>::type
f (T);

which can only be instantiated if T=int or T=double. A call to f('c') will just fail with a compiler error: "no instance of f(char) found". On the other hand, if the predicate in the first argument to the constraint_and_return_value template is true, then the return type is just the second type in the template.

Deprecated:
Use std::enable_if instead.
Author
Wolfgang Bangerth, 2003

Definition at line 174 of file template_constraints.h.


The documentation for this struct was generated from the following file: