Since named arguments can be passed in any order, they are
especially useful when a function or template has more than one
parameter with a useful default value. The library also supports
deduced parameters; that is to say, parameters whose identity
can be deduced from their types.

In C++, arguments are normally given meaning by their positions
with respect to a parameter list: the first argument passed maps
onto the first parameter in a function's definition, and so on.
That protocol is fine when there is at most one parameter with a
default value, but when there are even a few useful defaults, the
positional interface becomes burdensome:

Since an argument's meaning is given by its position, we have to
choose an (often arbitrary) order for parameters with default
values, making some combinations of defaults unusable:

In the example above we wanted to make an unmoveable window
with a default border_width, but instead we got a moveable
window with a border_width of zero. To get the desired
effect, we'd need to write:

A deduced parameter can be passed in any position without
supplying an explicit parameter name. It's not uncommon for a
function to have parameters that can be uniquely identified based
on the types of arguments passed. The name parameter to
new_window is one such example. None of the other arguments,
if valid, can reasonably be converted to a char const*. With
a deduced parameter interface, we could pass the window name in
any argument position without causing ambiguity:

The reasoning we've given for named and deduced parameter
interfaces applies equally well to class templates as it does to
functions. Using the Parameter library, we can create interfaces
that allow template arguments (in this case shared and
Client) to be explicitly named, like this:

smart_ptr<ownership<shared>, value_type<Client> > p;

The syntax for passing named template arguments is not quite as
natural as it is for function arguments (ideally, we'd be able to
write smart_ptr<ownership=shared,…>). This small syntactic
deficiency makes deduced parameters an especially big win when
used with class templates:

2.1.1 Headers And Namespaces

Most components of the Parameter library are declared in a
header named for the component. For example,

#include <boost/parameter/keyword.hpp>

will ensure boost::parameter::keyword is known to the
compiler. There is also a combined header,
boost/parameter.hpp, that includes most of the library's
components. For the the rest of this tutorial, unless we say
otherwise, you can use the rule above to figure out which header
to #include to access any given component of the library.

Also, the examples below will also be written as if the
namespace alias

namespace parameter = boost::parameter;

has been declared: we'll write parameter::xxx instead of
boost::parameter::xxx.

2.1.2 The Abstract Interface to depth_first_search

The Graph library's depth_first_search algorithm is a generic function accepting
from one to four arguments by reference. If all arguments were
required, its signature might be as follows:

an iterator_property_map
created from a std::vector of
default_color_type of size
num_vertices(graph) and using
index_map for the index map.

Don't be intimidated by the information in the second and third
columns above. For the purposes of this exercise, you don't need
to understand them in detail.

2.1.3 Defining the Keywords

The point of this exercise is to make it possible to call
depth_first_search with named arguments, leaving out any
arguments for which the default is appropriate:

graphs::depth_first_search(g, color_map_=my_color_map);

To make that syntax legal, there needs to be an object called
“color_map_” whose assignment operator can accept a
my_color_map argument. In this step we'll create one such
keyword object for each parameter. Each keyword object will be
identified by a unique keyword tag type.

It defines a keyword tag type named tag::graph and a keyword
object reference named _graph.

This “fancy dance” involving an unnamed namespace and references
is all done to avoid violating the One Definition Rule (ODR)2 when the named parameter interface is used by function
templates that are instantiated in multiple translation
units (MSVC6.x users see this note).

2.1.4 Writing the Function

Now that we have our keywords defined, the function template
definition follows a simple pattern using the
BOOST_PARAMETER_FUNCTION macro:

The return type of the resulting function template. Parentheses
around the return type prevent any commas it might contain from
confusing the preprocessor, and are always required.

The name of the resulting function template.

The name of a namespace where we can find tag types whose names
match the function's parameter names.

The function signature.

2.1.5 Function Signatures

Function signatures are described as one or two adjacent
parenthesized terms (a Boost.Preprocessorsequence) describing
the function's parameters in the order in which they'd be expected
if passed positionally. Any required parameters must come first,
but the (required … ) clause can be omitted when all the
parameters are optional.

2.1.5.1 Required Parameters

Required parameters are given first—nested in a (required … )
clause—as a series of two-element tuples describing each parameter
name and any requirements on the argument type. In this case there
is only a single required parameter, so there's just a single
tuple:

(required (graph, *) )

Since depth_first_search doesn't require any particular type
for its graph parameter, we use an asterix to indicate that
any type is allowed. Required parameters must always precede any
optional parameters in a signature, but if there are no
required parameters, the (required … ) clause can be omitted
entirely.

2.1.5.2 Optional Parameters

Optional parameters—nested in an (optional … ) clause—are given
as a series of adjacent three-element tuples describing the
parameter name, any requirements on the argument type, and and an
expression representing the parameter's default value:

2.1.5.3 Handling “Out” Parameters

Within the function body, a parameter name such as visitor is
a C++ reference, bound either to an actual argument passed by
the caller or to the result of evaluating a default expression.
In most cases, parameter types are of the form T const& for
some T. Parameters whose values are expected to be modified,
however, must be passed by reference to non-const. To
indicate that color_map is both read and written, we wrap
its name in in_out(…):

If color_map were strictly going to be modified but not examined,
we could have written out(color_map). There is no functional
difference between out and in_out; the library provides
both so you can make your interfaces more self-documenting.

2.1.5.4 Positional Arguments

When arguments are passed positionally (without the use of
keywords), they will be mapped onto parameters in the order the
parameters are given in the signature, so for example in this
call

graphs::depth_first_search(x, y);

x will always be interpreted as a graph and y will always
be interpreted as a visitor.

2.1.5.5 Default Expression Evaluation

Note that in our example, the value of the graph parameter is
used in the default expressions for root_vertex,
index_map and color_map.

A default expression is evaluated in the context of all preceding
parameters, so you can use any of their values by name.

A default expression is never evaluated—or even instantiated—if
an actual argument is passed for that parameter. We can actually
demonstrate that with our code so far by replacing the body of
depth_first_search with something that prints the arguments:

Despite the fact that default expressions such as
vertices(graph).first are ill-formed for the given graph
arguments, both calls will compile, and each one will print
exactly the same thing.

2.1.5.6 Signature Matching and Overloading

In fact, the function signature is so general that any call to
depth_first_search with fewer than five arguments will match
our function, provided we pass something for the required
graph parameter. That might not seem to be a problem at first;
after all, if the arguments don't match the requirements imposed by
the implementation of depth_first_search, a compilation error
will occur later, when its body is instantiated.

There are at least three problems with very general function
signatures.

By the time our depth_first_search is instantiated, it has
been selected as the best matching overload. Some other
depth_first_search overload might've worked had it been
chosen instead. By the time we see a compilation error, there's
no chance to change that decision.

Even if there are no overloads, error messages generated at
instantiation time usually expose users to confusing
implementation details. For example, users might see references
to names generated by BOOST_PARAMETER_FUNCTION such as
graphs::detail::depth_first_search_with_named_params (or
worse—think of the kinds of errors you get from your STL
implementation when you make a mistake).4

The problems with exposing such permissive function template
signatures have been the subject of much discussion, especially
in the presence of unqualified calls. If all we want is to
avoid unintentional argument-dependent lookup (ADL), we can
isolate depth_first_search in a namespace containing no
types6, but suppose we want it to found via ADL?

It's usually a good idea to prevent functions from being considered
for overload resolution when the passed argument types aren't
appropriate. The library already does this when the required
graph parameter is not supplied, but we're not likely to see a
depth first search that doesn't take a graph to operate on.
Suppose, instead, that we found a different depth first search
algorithm that could work on graphs that don't model
Incidence Graph? If we just added a simple overload,
it would be ambiguous:

2.1.5.6.1 Adding Type Requirements

We really don't want the compiler to consider the original version
of depth_first_search because the root_vertex argument,
"hello", doesn't meet the requirement that it match the
graph parameter's vertex descriptor type. Instead, this call
should just invoke our new overload. To take the original
depth_first_search overload out of contention, we need to tell
the library about this requirement by replacing the * element
of the signature with the required type, in parentheses:

Now the original depth_first_search will only be called when
the root_vertex argument can be converted to the graph's vertex
descriptor type, and our example that was ambiguous will smoothly
call the new overload.

Note

The type of the graph argument is available in the
signature—and in the function body—as graph_type. In
general, to access the type of any parameter foo, write foo_type.

2.1.5.6.2 Predicate Requirements

The requirements on other arguments are a bit more interesting than
those on root_vertex; they can't be described in terms of simple
type matching. Instead, they must be described in terms of MPL
Metafunctions. There's no space to give a complete description
of metafunctions or of graph library details here, but we'll show
you the complete signature with maximal checking, just to give you
a feel for how it's done. Each predicate metafunction is enclosed
in parentheses and preceded by an asterix, as follows:

Intended to be used to access preceding arguments types in the
predicates.

We acknowledge that this signature is pretty hairy looking.
Fortunately, it usually isn't necessary to so completely encode the
type requirements on arguments to generic functions. However, it
is usally worth the effort to do so: your code will be more
self-documenting and will often provide a better user experience.
You'll also have an easier transition to an upcoming C++ standard
with language support for concepts.

2.1.5.7 Deduced Parameters

To illustrate deduced parameter support we'll have to leave behind
our example from the Graph library. Instead, consider the example
of the def function from Boost.Python. Its signature is
roughly as follows:

Try not to be too distracted by the use of the term “keywords” in
this example: although it means something analogous in Boost.Python
to what it means in the Parameter library, for the purposes of this
exercise you can think of it as being completely different.

When calling def, only two arguments are required. The
association between any additional arguments and their parameters
can be determined by the types of the arguments actually passed, so
the caller is neither required to remember argument positions or
explicitly specify parameter names for those arguments. To
generate this interface using BOOST_PARAMETER_FUNCTION, we need
only enclose the deduced parameters in a (deduced …) clause, as
follows:

The BOOST_PARAMETER_MEMBER_FUNCTION and
BOOST_PARAMETER_CONST_MEMBER_FUNCTION macros accept exactly the
same arguments as BOOST_PARAMETER_FUNCTION, but are designed to
be used within the body of a class:

The lack of a “delegating constructor”
feature in C++
(http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1986.pdf)
limits somewhat the quality of interface this library can provide
for defining parameter-enabled constructors. The usual workaround
for a lack of constructor delegation applies: one must factor the
common logic into a base class.

Let's build a parameter-enabled constructor that simply prints its
arguments. The first step is to write a base class whose
constructor accepts a single argument known as an ArgumentPack:
a bundle of references to the actual arguments, tagged with their
keywords. The values of the actual arguments are extracted from
the ArgumentPack by indexing it with keyword objects:

Note that the bitwise or (“|”) operator has a special
meaning when applied to keyword objects that are passed to an
ArgumentPack's indexing operator: it is used to indicate a
default value. In this case if there is no index parameter in
the ArgumentPack, 42 will be used instead.

Now we are ready to write the parameter-enabled constructor
interface:

It defines a keyword tag type named tag::class_type and a
parameter passing template named class_type.

2.4.1.2 Class Template Skeleton

The next step is to define the skeleton of our class template,
which has three optional parameters. Because the user may pass
arguments in any order, we don't know the actual identities of
these parameters, so it would be premature to use descriptive names
or write out the actual default values for any of them. Instead,
we'll give them generic names and use the special type
boost::parameter::void_ as a default:

2.4.1.3 Class Template Signatures

Next, we need to build a type, known as a ParameterSpec,
describing the “signature” of boost::python::class_. A
ParameterSpec enumerates the required and optional parameters in
their positional order, along with any type requirements (note that
it does not specify defaults -- those will be dealt with
separately):

2.4.1.4 Argument Packs and Parameter Extraction

Next, within the body of class_ , we use the ParameterSpec's
nested ::bind< … > template to bundle the actual arguments into an
ArgumentPack type, and then use the library's value_type< … >
metafunction to extract “logical parameters”. value_type< … > is
a lot like binding< … >, but no reference is added to the actual
argument type. Note that defaults are specified by passing it an
optional third argument:

2.4.3 Deduced Template Parameters

To apply a deduced parameter interface here, we need only make the
type requirements a bit tighter so the held_type and
copyable parameters can be crisply distinguished from the
others. Boost.Python does this by requiring that base_list be
a specialization of its bases< … > template (as opposed to
being any old MPL sequence) and by requiring that copyable, if
explicitly supplied, be boost::noncopyable. One easy way of
identifying specializations of bases< … > is to derive them all
from the same class, as an implementation detail:

If you don't like the leading-underscore naming convention used
to refer to keyword objects, or you need the name tag for
something other than the keyword type namespace, there's another
way to use BOOST_PARAMETER_NAME:

We've already seen ArgumentPacks when we looked at
parameter-enabled constructors and class templates. As you
might have guessed, ArgumentPacks actually lie at the heart of
everything this library does; in this section we'll examine ways to
build and manipulate them more effectively.

3.2.1 Building ArgumentPacks

The simplest ArgumentPack is the result of assigning into a
keyword object:

To build an ArgumentPack with positional arguments, we can use a
ParameterSpec. As introduced described in the section on Class
Template Signatures, a ParameterSpec describes the positional
order of parameters and any associated type requirements. Just as
we can build an ArgumentPacktype with its nested ::bind< …
> template, we can build an ArgumentPackobject by invoking
its function call operator:

Note that because of the forwarding problem, parameter::parameters::operator()
can't accept non-const rvalues.

3.2.2 Extracting Parameter Types

If we want to know the types of the arguments passed to
print_name_and_index, we have a couple of options. The
simplest and least error-prone approach is to forward them to a
function template and allow it to do type deduction:

Occasionally one needs to deduce argument types without an extra
layer of function call. For example, suppose we wanted to return
twice the value of the index parameter? In that
case we can use the value_type< … > metafunction introduced
earlier:

Note that if we had used binding< … > rather than value_type< …
>, we would end up returning a reference to the temporary created in
the 2 * … expression.

3.2.3 Lazy Default Computation

When a default value is expensive to compute, it would be
preferable to avoid it until we're sure it's absolutely necessary.
BOOST_PARAMETER_FUNCTION takes care of that problem for us, but
when using ArgumentPacks explicitly, we need a tool other than
operator|:

In the example above, the string "hello, world" is constructed
despite the fact that the user passed us a value for s3. To
remedy that, we can compute the default value lazily (that is,
only on demand), by using boost::bind() to create a function
object.

To remember the difference between | and ||, recall that
|| normally uses short-circuit evaluation: its second
argument is only evaluated if its first argument is false.
Similarly, in color_map[param||f], f is only invoked if
no color_map argument was supplied.

The expression bind(std::plus<std::string>(), ref(s1), ref(s2)) yields
a function object that, when invoked, adds the two strings together.
That function will only be invoked if no s3 argument is supplied by
the caller.

Although in the case above, the user was trying to pass the value
3 as the age parameter to g, what happened instead
was that f's age argument got reassigned the value 3,
and was then passed as a positional argument to g. Since
g's first positional parameter is name, the default value
for age is used, and g prints 3:42. Our leading
underscore naming convention that makes this problem less likely
to occur.

In this particular case, the problem could have been detected if
f's age parameter had been made const, which is always a
good idea whenever possible. Finally, we recommend that you use
an enclosing namespace for all your code, but particularly for
names with leading underscores. If we were to leave out the
people namespace above, names in the global namespace
beginning with leading underscores—which are reserved to your C++
compiler—might become irretrievably ambiguous with those in our
unnamed namespace.

Use the regression test results for the latest Boost release of
the Parameter library to see how it fares on your favorite
compiler. Additionally, you may need to be aware of the following
issues and workarounds for particular compilers.

Some older compilers don't support SFINAE. If your compiler meets
that criterion, then Boost headers will #define the preprocessor
symbol BOOST_NO_SFINAE, and parameter-enabled functions won't be
removed from the overload set based on their signatures.

Lazy default computation relies on the result_of class
template to compute the types of default arguments given the type
of the function object that constructs them. On compilers that
don't support result_of, BOOST_NO_RESULT_OF will be
#defined, and the compiler will expect the function object to
contain a nested type name, result_type, that indicates its
return type when invoked without arguments. To use an ordinary
function as a default generator on those compilers, you'll need to
wrap it in a class that provides result_type as a typedef
and invokes the function via its operator().

If you use Microsoft Visual C++ 6.x, you may find that the compiler
has trouble finding your keyword objects. This problem has been
observed, but only on this one compiler, and it disappeared as the
test code evolved, so we suggest you use it only as a last resort
rather than as a preventative measure. The solution is to add
using-declarations to force the names to be available in the
enclosing namespace without qualification:

namespace graphs
{
using graphs::graph;
using graphs::visitor;
using graphs::root_vertex;
using graphs::index_map;
using graphs::color_map;
}

As of Boost 1.33.0 the Graph library was still
using an older named parameter mechanism, but there are
plans to change it to use Boost.Parameter (this library) in an
upcoming release, while keeping the old interface available for
backward-compatibility.

The One Definition Rule says that any given entity in
a C++ program must have the same definition in all translation
units (object files) that make up a program.

[3]

If you're not familiar with the Boost Graph
Library, don't worry about the meaning of any
Graph-library-specific details you encounter. In this case you
could replace all mentions of vertex descriptor types with
int in the text, and your understanding of the Parameter
library wouldn't suffer.

This capability depends on your compiler's support for SFINAE.
SFINAE: Substitution Failure Is
Not An E rror. If type substitution during the
instantiation of a function template results in an invalid type,
no compilation error is emitted; instead the overload is removed
from the overload set. By producing an invalid type in the
function signature depending on the result of some condition,
we can decide whether or not an overload is considered during overload
resolution. The technique is formalized in
the enable_if utility. Most recent compilers support SFINAE;
on compilers that don't support it, the Boost config library
will #define the symbol BOOST_NO_SFINAE.
See
http://www.semantics.org/once_weakly/w02_SFINAE.pdf for more
information on SFINAE.