gpt4 book ai didi

c++ - 如何在 boost::xpressive 语义操作中使用 "new"运算符?

转载 作者:太空宇宙 更新时间:2023-11-04 12:14:39 25 4
gpt4 key购买 nike

似乎 boost::xpressive 没有提供 new 运算符的惰性评估版本,所以这个语义操作不会编译:

using namespace boost::xpressive ;
std::vector<int*> vec ;

// Match any integer and capture into s1.
// Then use a semantic action to push it onto vec.
sregex num = (s1= +digit)[ ref(vec)->*push_back( new as<int>(s1) ) ] ;

是否有在语义操作中使用 new 运算符的结构?例如,boost::phoenix 提供了 new_ lambda 函数。 xpressive 是否为语义 Action 提供了类似的东西?

最佳答案

这是迄今为止我想到的最好的。此代码定义了一个函数,允许您使用语法 new_<T>::with(...)作为相当于 new T(...) 的语义 Action .该函数以 lazy function example 为模型在boost xpressive user guide . (下面的代码片段只支持最多有 2 个参数的构造函数,但添加更多参数只是复制/粘贴的问题。)

using namespace boost::xpressive ;

template <typename _ObjectType>
struct new_impl
{
typedef _ObjectType* result_type;

_ObjectType* operator()() const
{
return new _ObjectType() ;
}

template<typename _T0>
_ObjectType* operator()(_T0 const &a0) const
{
return new _ObjectType( a0 ) ;
}

template<typename _T0, typename _T1>
_ObjectType* operator()(_T0 const &a0, _T1 const &a1) const
{
return new _ObjectType( a0, a1 ) ;
}
};

template <typename _ObjectType>
struct new_
{
static const typename function<new_impl<_ObjectType> >::type with ;
};
template <typename _ObjectType>
const typename function<new_impl<_ObjectType> >::type new_<_ObjectType>::with = {{}};

这是实际操作:

int main()
{
std::vector<int*> vec ;

// Matches an integer, with a semantic action to push it onto vec
sregex num = (s1= +digit)
[ ref(vec)->*push_back( new_<int>::with( as<int>(s1) ) ) ] ;

// Space-delimited list of nums
sregex num_list = num >> *(' ' >> num) ;

std::string str = "8 9 10 11" ;
if ( regex_match( str, num_list ) )
{
std::cout << "Found an int list: " ;
BOOST_FOREACH( int* p, vec )
{
std::cout << *p << ' ' ;
}
}
else
{
std::cout << "Didn't find an int list." ;
}

return 0 ;
}

输出:

Found an int list: 8 9 10 11

为了提高上面代码的通用性,最好将参数类型更改为使用boost::add_reference<>。和 boost::add_const<> ,但你明白了。

关于c++ - 如何在 boost::xpressive 语义操作中使用 "new"运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8313317/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com