Boost C++ 库

……世界上最受推崇、设计最精良的 C++ 库项目之一。 Herb SutterAndrei Alexandrescu, C++ Coding Standards

Struct 模板占位符 - Boost C++ 函数库
PrevUpHomeNext

Struct 模板占位符

boost::xpressive::placeholder — 用于定义一个占位符,以代表用于语义操作的变量。

提要

// In header: <boost/xpressive/xpressive_fwd.hpp>

template<typename T, int I = 0> 
struct placeholder {

  // public member functions
  unspecified operator=(T &) const;
  unspecified operator=(T const &) const;
};

描述

使用 placeholder<> 定义一个占位符,用于语义操作中代表真实对象。占位符的使用允许一次定义带有操作的正则表达式,并在许多上下文中重用,以便在定义正则表达式时不可用的对象进行读写。

您可以通过创建 placeholder<T> 类型的对象,并在语义操作中使用该对象,就像您打算使用 T 类型对象一样,来使用 placeholder<>

placeholder<int> _i;
placeholder<double> _d;

sregex rex = ( some >> regex >> here )
    [ ++_i, _d *= _d ];

然后,在进行模式匹配时,无论是使用 regex_search()regex_match() 还是 regex_replace(),请传递一个 match_results<> 对象,该对象包含用于正则表达式对象语义操作中使用的占位符的绑定。您可以通过调用 match_results::let 来创建绑定,如下所示:

int i = 0;
double d = 3.14;

smatch what;
what.let(_i = i)
    .let(_d = d);

if(regex_match("some string", rex, what))
   // i and d mutated here

如果执行的语义操作包含未绑定的占位符,则会抛出 regex_error 类型的异常。

有关更多信息,请参阅 xpressive::let() 的讨论以及用户指南中“引用非局部变量”部分。

示例

// Define a placeholder for a map object:
placeholder<std::map<std::string, int> > _map;

// Match a word and an integer, separated by =>,
// and then stuff the result into a std::map<>
sregex pair = ( (s1= +_w) >> "=>" >> (s2= +_d) )
    [ _map[s1] = as<int>(s2) ];

// Match one or more word/integer pairs, separated
// by whitespace.
sregex rx = pair >> *(+_s >> pair);

// The string to parse
std::string str("aaa=>1 bbb=>23 ccc=>456");

// Here is the actual map to fill in:
std::map<std::string, int> result;

// Bind the _map placeholder to the actual map
smatch what;
what.let( _map = result );

// Execute the match and fill in result map
if(regex_match(str, what, rx))
{
    std::cout << result["aaa"] << '\n';
    std::cout << result["bbb"] << '\n';
    std::cout << result["ccc"] << '\n';
}

模板参数

  1. typename T

    此占位符所代表对象的类型。

  2. int I = 0

    一个可选标识符,可用于区分在同一语义操作中可能使用的其他占位符,这些占位符恰好具有相同的类型。

placeholder 公共成员函数

  1. unspecified operator=(T & t) const;

    参数

    t

    要与此占位符关联的对象

    返回

    一个未指定类型的对象,它记录了 t*this 的关联。

  2. unspecified operator=(T const & t) const;
    这是一个重载的成员函数,为方便起见提供。它仅在接受的参数不同时与上述函数有所区别。

PrevUpHomeNext