Карта сайта Kansoftware
НОВОСТИУСЛУГИРЕШЕНИЯКОНТАКТЫ
Разработка программного обеспечения

The Boost Parameter Library Reference Documentation

Boost , ,

Boost C++ Libraries

...one of the most highly regarded and expertly designed C++ library projects in the world. Herb Sutter and Andrei Alexandrescu, C++ Coding Standards

The Boost Parameter Library Reference Documentation

Authors: Давид Абрахамс
Дэниел Уоллин
Contact: Этот раздел охватывает некоторые основные сведения, которые вам нужно знать, чтобы понять эту ссылку.

1.1   Namespaces

В этом документе все неквалифицированные идентификаторы должны быть определены в пространстве именboost::parameter., если не указано иное.

1.2   Exceptions

Никакая операция, описанная в этом документе, не предусматривает исключения, если не указано иное.

1.3   Thread Safety

Все компоненты этой библиотеки можно безопасно использовать из нескольких потоков без синхронизации.1

1.4   Typography

Имена, написанные вбез засечек, представляютпонятия.

В кодовых блокахкурсивомпредставлен неуточненный текст, удовлетворяющий требованиям, приведенным в подробном описании, которое следует за кодовым блоком.

В спецификации токенов, генерируемых макросом,жирный типиспользуется для выделения позиции расширенного макроаргумента в результате.

Специальный символ β представляет значение.BOOST_PARAMETER_MAX_ARITY.


2   Terminology

keyword
The name of a function parameter.
keyword tag type
A type used to uniquely identify a function parameter. Typically its name will be the same as that of the parameter.
positional argument
An argument passed with no explicit keyword. Its parameter is determined in the usual C++ way: by position with respect to a parameter list.
tag type
Shorthand for “keyword tag type.”
keyword object
An instance of keyword <T> for some tag type T.
tagged reference

An object whose type is associated with a keyword tag type (the object's keyword), and that holds a reference (to the object's value).

As a shorthand, a “tagged reference to x” means a tagged reference whose value is x.

tagged default
A tagged reference whose value represents the value of a default argument.
tagged lazy default
A tagged reference whose value, when invoked with no arguments, computes a default argument value.
intended argument type
The intended argument type of a single-element ArgumentPack is the type of its element's value. The intended argument type of any other type X is X itself.

Note

In this reference, we will use concept names (and other names) to describe both types and objects, depending on context. So for example, “an ArgumentPack” can refer to a type that models ArgumentPack or an object of such a type.


3   Concepts

Этот раздел описывает общие понятия типа, используемые библиотекой параметров.

3.1   ArgumentPack

ArgumentPackпредставляет собой наборпомеченных ссылокs на фактические аргументы, переданные функции. КаждыйArgumentPackтакже является действительным MPL.Передовая последовательность, состоящая изтипа тега ключевого словав егопомеченной ссылке.

Requirements

В таблице ниже,

Любые исключения из призываwзначениебудет распространяться на вызывающего.

ArgumentPack requirements
Expression Type Requirements Semantics/Notes
x[u] связывание::type xсодержит элементb, ключевое словокоторогоK Возвращаетбзначение(по ссылке).
x[u] связывание::type Нет Еслиxсодержит элементb, ключевое словокоторогосовпадает сu's, возвращаетb's(по ссылке). В противном случае возвращаетузначение.
x[w] lazy_binding::type Нет Еслиxсодержит элементb, ключевое словокоторого совпадает сw's, возвращаетbзначение(по ссылке). В противном случае вызываетw'sи возвращает результат.
x, z МодельArgumentPack Нет ВозвращаетArgumentPackсодержит все элементыxиz.

3.2   ParameterSpec

ParameterSpecописывает требования типа для аргументов, соответствующих данномуключевому слову, и указывает, является ли аргумент необязательным или обязательным. В таблице ниже подробно описаны разрешенные формы и описано их состояние для удовлетворения фактическим типом аргумента. В каждом ряду,

ParameterSpec allowed forms and conditions of satisfaction
Type A required Condition A must satisfy
К нет n/a
необязательно нет mpl::apply::type::valueявляетсяистинным.
требуется да mpl::apply::type::valueявляетсяистинным.

Информация вParameterSpecиспользуется дляограниченияаргументов, которые будут соответствоватьфункциям пересылки.


4   Class Templates

4.1   keyword

Тип каждогообъекта ключевых словявляется специализациейключевого слова.

Defined in:boost/parameter/keyword.hpp
template <class Tag>
struct keyword
{
    template <class T> ArgumentPack operator=(T& value) const;
    template <class T> ArgumentPack operator=(T const& value) const;
    template <class T> tagged default operator|(T& x) const;
    template <class T> tagged default operator|(T const& x) const;
    template <class F> tagged lazy default operator||(F const&) const;
    static keyword<Tag>& get();
};
operator=
template <class T> ArgumentPack operator=(T& value) const;
template <class T> ArgumentPack operator=(T const& value) const;
Requires:nothing
Returns:an ArgumentPack containing a single tagged reference to value with keyword Tag
operator|
template <class T> tagged default operator|(T& x) const;
template <class T> tagged default operator|(T const& x) const;
Returns:a tagged default with value x and keyword Tag.
operator||
template <class F> tagged lazy default operator||(F const& g) const;
Requires:g() is valid, with type boost::result_of<F()>::type.2
Returns:a tagged lazy default with value g and keyword Tag.
get
static keyword<Tag>& get();
Returns:a “singleton instance”: the same object will be returned on each invocation of get().
Thread Safety:get() can be called from multiple threads simultaneously.

4.2   parameters

Предоставляет интерфейс для сборки фактических аргументов впередающую функциювArgumentPack, в котором любыепозиционныеаргументы будут помечены в соответствии с соответствующим шаблонным аргументом впараметры.

Defined in:boost/parameter/parameters.hpp
template <class P0 = unspecified, class P1 = unspecified, …class Pβ = unspecified>
struct parameters
{
    template <class A0, class A1 = unspecified, …class Aβ = unspecified>
    struct match
    {
        typedef … type;
    };
    template <class A0>
    ArgumentPack operator()(A0& a0) const;
    template <class A0, class A1>
    ArgumentPack operator()(A0& a0, A1& a1) const;
    
    template <class A0, class A1, …class Aβ>
    ArgumentPack operator()(A0& a0, A1& a1, …Aβ& aβ) const;
};
Requires:P0, P1, … Pβ are models of ParameterSpec.

Note

В этом разделеRiиKiопределяются следующим образом для любого типа аргументаAi:

let D0 the set [d0, …, dj] of all deduced parameter specs in [P0, …, Pβ]

if Ai is a result type of keyword<T>::operator=
then
Кi is T
else
if some Aj where ji is a result type of keyword<T>::operator=
or some Pj in ji is deduced
then
if some parameter spec dj in Di matches Ai
then
Кi is dj's keyword tag type.
Di+1 is Di - [dj]
else
Кi is Pi's keyword tag type.
match

A Metafunction used to remove a forwarding function from overload resolution.

Returns:if P0, P1, …Pβ are satisfied (see below), then parameters<P0,P1,…Pβ>. Otherwise, match<A0,A1,…Aβ>::type is not defined.

P0,P1, ...Pβудовлетворены, если для каждогоjв 0...β:

  • Pjявляетсянеопределеннымпо умолчанию
  • или,Pj- этотип тега ключевого слова
  • или,Pjявляетсяфакультативными либо
    • не являетсяKiдля любогоi,
    • илиXпредставляет собой некотороеKiиmpl::applyi>::type::valueявляетсяистинным.
  • или,Pjтребуетсятребуется, а
    • X— это некотороеKi,и.
    • mpl::applyi>::type::valueявляетсяистинным
operator()
template <class A0> ArgumentPack operator()(A0 const& a0) const;

template <class A0, …class Aβ> ArgumentPack operator()(A0 const& a0, …Aβ const& aβ) const;
Returns:

An ArgumentPack containing, for each ai,

4.3   optional, required

Эти шаблоны описывают требования к параметру функции.

Defined in:boost/parameter/parameters.hpp
Specializations model:
 ParameterSpec
template <class Tag, class Predicate = unspecified>
struct optional;
template <class Tag, class Predicate = unspecified>
struct required;

Значение по умолчаниюПредикатаявляется неопределенным.Метафункция, возвращающаяmpl::true_для любого аргумента.

4.4   deduced

Этот шаблон используется для обертывания аргументатега ключевого словадонеобязательногоилитребуемого.

Defined in:boost/parameter/parameters.hpp
template <class Tag>
struct deduced;

5   Metafunctions

Метафункцияконцептуально является функцией, которая работает на типах C++ и возвращает их.

5.1   binding

Возвращает тип результата индексации пакета аргументов стипом тега ключевых словили спомеченным по умолчанию.

Defined n:boost/parameter/binding.hpp
template <class A, class K, class D = void>
struct binding
{
    typedef … type;
};
Requires:A is a model of ArgumentPack.
Returns:the reference type of the tagged reference in A having keyword tag type K, if any. If no such tagged reference exists, returns D.

5.2   lazy_binding

Возвращает тип результата индексации пакета аргументов с помеченным ленивым по умолчанию.

Defined in:boost/parameter/binding.hpp
template <class A, class K, class F>
struct lazy_binding
{
    typedef … type;
};
Requires:A is a model of ArgumentPack.
Returns:the reference type of the tagged reference in A having keyword tag type K, if any. If no such tagged reference exists, returns boost::result_of<F()>::type.2

5.3   value_type

Возвращает тип результата индексации пакета аргументов стипом тега ключевых словили спомеченным по умолчанию.

Defined n:boost/parameter/value_type.hpp
template <class A, class K, class D = void>
struct value_type
{
    typedef … type;
};
Requires:

A is a model of ArgumentPack.

Returns:

the type of the tagged reference in A having keyword tag type K, if any. If no such tagged reference exists, returns D. Equivalent to:

typename remove_reference<
  typename binding<A, K, D>::type
>::type

… when D is not a reference type.


6   Code Generation Macros

Макрос в этом разделе может быть использован для облегчения написания кода с помощью параметра libray путем устранения повторяющихся шаблонов.

6.1   BOOST_PARAMETER_FUNCTION(result,name,tag_namespace,arguments)

Defined in:boost/parameter/preprocessor.hpp
Requires:

result is the parenthesized return type of the function. name is the base name of the function, this is the name of the generated forwarding functions. tag_namespace is the namespace in which the keywords used by the function resides. arguments is a list of argument specifiers, as defined below.

Argument specifiers syntax:
 
argument-specifiers ::= specifier-group {specifier-group}
specifier-group0 ::= specifier-group1 |
                     ( '(' 'deduced' specifier-group1 {specifier-group1} ')' )
specifier-group1 ::= ( '(' 'optional' optional-specifier {optional-specifier} ')' ) |
                     ( '(' 'required' required-specifier {required-specifier} ')' )
optional-specifier ::= '(' name ',' restriction ',' default-value ')'
required-specifier ::= '(' name ',' restriction ')'
restriction ::= ('*' '(' lambda-expression ')' ) |
                ( '(' typename ')' ) |
                '*'

name is any valid C++ identifier. default-value is any valid C++ expression. typename is the name of a type. lambda-expression is an MPL lambda expression.

Generated names in enclosing scope:
 
  • boost_param_result_##_LINE__## Имя
  • boost_param_params_ ## __LINE__ ## Имя
  • boost_param_parameters_ ## __LINE__ ## Имя
  • boost_param_impl ## name
  • boost_param_default_##_LINE__## Имя
Approximate expansion:

Where:

  • nобозначаетминимум, как определено изаргументов.
  • mобозначаетмаксимальнуюпрочность, как определено изаргументов.
template <class T>
struct boost_param_result_ ## __LINE__ ## name
{
    typedef result type;
};
struct boost_param_params_ ## __LINE__ ## name
  : boost::parameter::parameters<
        list of parameter specifications, based on arguments
    >
{};
typedef boost_param_params_ ## __LINE__ ## name
  boost_param_parameters_ ## __LINE__ ## name;
template <class A0, …, class An>
result type name(
    A0 cv& a0, …, An cv& an
  , typename boost_param_parameters_ ## __LINE__ ## name::match<
      A0 cv, …, An cv
    >::type = boost_param_parameters_ ## __LINE__ ## name()
)
{
    … forward to implementation …
}

template <class A0, …, class Am>
result type name(
    A0 cv& a0, …, Am cv& am
  , typename boost_param_parameters_ ## __LINE__ ## name::match<
      A0 cv, …, Am cv
    >::type = boost_param_parameters_ ## __LINE__ ## name()
)
{
    … forward to implementation …
}
template <
    class ResultType
  , class argument name0 ## _type
    …
  , class argument namem ## _type
>
ResultType boost_param_default_ ## __LINE__ ## name(
    (ResultType(*)())
  , argument name0 ## _type& argument name0
    …
  , argument namem ## _type& argument namem
)

6.2   BOOST_PARAMETER_MEMBER_FUNCTION(result,name,tag_namespace,arguments)

Defined in:boost/parameter/preprocessor.hpp

См.BOOST_PARAMETER_FUNCTION (результат, имя, тег_namespace, аргументы)

6.3   BOOST_PARAMETER_CONSTRUCTOR(cls, impl, tag_namespace, arguments)

Defined in:boost/parameter/preprocessor.hpp
Requires:

cls is the name of this class. impl is the parenthesized implementation base class for cls. tag_namespace is the namespace in which the keywords used by the function resides. arguments is a list of argument specifiers, as defined in BOOST_PARAMETER_FUNCTION(result,name,tag_namespace,arguments).

Generated names in enclosing scope:
 
  • boost_param_params_ ## __LINE__ ## ctor
  • конструктор_параметры ## __LINE__
Approximate expansion:

Where:

  • nобозначаетминимум, как определено изаргументов.
  • mобозначаетмаксимальнуюпрочность, как определено изаргументов.
struct boost_param_params_ ## __LINE__ ## ctor
  : boost::parameter::parameters<
        list of parameter specifications, based on arguments
    >
{};
typedef boost_param_params_ ## __LINE__ ## name
  constructor_parameters ## __LINE__;
template <class A0, …, class An>
cls(A0 const& a0, …, An const& an)
  : impl(constructor_parameters ## __LINE__(a0, …, an))
{}

template <class A0, …, class Am>
cls(A0 const& a0, …, An const& am)
  : impl(constructor_parameters ## __LINE__(a0, …, am))
{}

6.4   BOOST_PARAMETER_NAME(name)

Объявляет тип тега и объект ключевого слова.

Расширяется до:

Еслиимяимеет вид:

(tag-name, namespace-name) object-name

тогда

namespace namespace-name
{
  struct tag-name
  {
      static char const* keyword_name()
      {
          return ##tag-name;
      }
      typedef unspecified _;
      typedef unspecified _1;
  };
}
::boost::parameter::keyword<tag-namespace::tag-name> const& object-name
    = ::boost::parameter::keyword<tag-namespace::tag-name>::instance;

Другое

namespace tag
{
  struct name
  {
      static char const* keyword_name()
      {
          return ##name;
      }
      typedef unspecified _;
      typedef unspecified _1;
  };
}
::boost::parameter::keyword<tag::name> const& _name
    = ::boost::parameter::keyword<tag::name>::instance;

6.5   BOOST_PARAMETER_TEMPLATE_KEYWORD(name)

Расширяется до:

namespace tag
{
  struct name;
}
template <class T>
struct name
  : ::boost::parameter::template_keyword<tag::name, T>
{};

6.6   BOOST_PARAMETER_FUN(r,n,l,h,p)

Deprecated

This macro has been deprecated in favor of BOOST_PARAMETER_FUNCTION.

Генерирует последовательностьфункции пересылкишаблонов, названныхn, с частотами, варьирующимися отlдоh, возвращаяrи используяpдля управления разрешением перегрузки и назначения меток позиционным аргументам.

Defined in:boost/parameter/macros.hpp
Requires:l and h are nonnegative integer tokens such that l < h
Generates
template <class A1, class A2, …class A##l>
r name(
    A1 const& a1, A2 const& a2, …Al const& xl
  , typename p::match<A1,A2,…Al>::type p = p())
{
   return name_with_named_params(p(x1,x2,…xl));
}
template <class A1, class A2, …class Al, class A##BOOST_PP_INC(l)>
r name(
    A1 const& a1, A2 const& a2, …Al const& xl
  , A##BOOST_PP_INC(l) const& x##BOOST_PP_INC(l)
  , typename p::match<A1,A2,…Al,A##BOOST_PP_INC(l)>::type p = p())
{
   return name_with_named_params(p(x1,x2,…xl,x##BOOST_PP_INC(l)));
}

template <class A1, class A2, …class Ah>
r name(
    A1 const& a1, A2 const& a2, …Ah const& xh
  , typename p::match<A1,A2,…Ah>::type p = p())
{
   return name_with_named_params(p(a1,a2,…ah));
}

6.7   BOOST_PARAMETER_KEYWORD(n,k)

Deprecated

This macro has been deprecated in favor of BOOST_PARAMETER_NAME.

Генерирует объявление типатега ключевого слова, названногоkв пространстве именn, и соответствующееопределение объекта ключевых словв замкнутом пространстве имен.

Defined in:boost/parameter/keyword.hpp
Generates
namespace n { struct k; }
namespace {
  boost::parameter::keyword<tag-namespace::k>& k
  = boost::parameter::keyword<tag-namespace::k>::get();
}

6.8   BOOST_PARAMETER_MATCH(p,a,x)

Создает декларацию параметров по умолчанию дляфункции пересылки.

Defined in:boost/parameter/match.hpp
Requires:

a is a Boost.Preprocessor sequence of the form

(A0)(A1)…(An)
Generates
typename p::match<A0,A1…,An>::type x = p()

7   Configuration Macros

7.1   BOOST_PARAMETER_MAX_ARITY

Определяет максимальное количество аргументов, поддерживаемых библиотекой. Библиотека будет определятьтолько в том случае, если она еще не определена.

Defined in:boost/parameter/config.hpp
Default Value:8

8   Tutorial

Нажмитена ссылку. Параметры учебной документации.


[1]Ссылки на объекты тегов могут быть инициализированы несколько раз. Такой сценарий может произойти только при наличии резьбы. Поскольку стандарт C++ не рассматривает потоковую передачу, он явно не разрешает или запрещает многократную инициализацию ссылок. Тем не менее, трудно представить реализацию, в которой это может иметь значение.
[2]1,2ГдеBOOST_NO_RESULT_OFявляется#определенным,повышением::результат_::typeзаменяетсяF::result_type.

Статья The Boost Parameter Library Reference Documentation раздела может быть полезна для разработчиков на c++ и boost.




Материалы статей собраны из открытых источников, владелец сайта не претендует на авторство. Там где авторство установить не удалось, материал подаётся без имени автора. В случае если Вы считаете, что Ваши права нарушены, пожалуйста, свяжитесь с владельцем сайта.



:: Главная :: ::


реклама


©KANSoftWare (разработка программного обеспечения, создание программ, создание интерактивных сайтов), 2007
Top.Mail.Ru

Время компиляции файла: 2024-08-30 11:47:00
2025-05-19 19:40:51/0.03341007232666/1