這是迄今爲止我所得出的最好結果。該代碼定義了一個函數,該函數允許您使用語法new_<T>::with(...)
作爲等效於new T(...)
的語義操作。該功能在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<>
,但您明白了。