2011-11-29 47 views
1

看來的boost :: xpressive中不提供new運營商的評價懶洋洋的版本,所以這個語義動作不會編譯:如何在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爲lambda提供了new_函數。 xpressive是否提供了類似的語義操作?

回答

1

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

相關問題