这是迄今为止我想出的最好的。此代码定义了一个函数,允许您将语法new_<T>::with(...)
用作等效于new T(...)
. 该函数仿照boost xpressive 用户指南中的惰性函数示例。(下面的代码片段只支持最多有 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<>
and boost::add_const<>
,但你明白了。