使用boost foreach和自己模板的项目

Bee*_*and 3 c++ boost boost-foreach

我有一个std::deque< std::pair<int, int> >我想迭代使用BOOST_FOREACH.

我尝试了以下方法:

  #define foreach_ BOOST_FOREACH

  // declaration of the std::deque
  std::deque< std::pair<int, int> > chosen;

  foreach_( std::pair<int,int> p, chosen )
  {
     ... 
  }
Run Code Online (Sandbox Code Playgroud)

但是当我编译它(在Visual Studio中)时,我收到以下错误:

warning C4002: too many actual parameters for macro 'BOOST_FOREACH'
1>c:\users\beeband\tests.cpp(133): error C2143: syntax error : missing ')' before '>'
1>c:\users\beeband\tests.cpp(133): error C2059: syntax error : '>'
1>c:\users\beeband\tests.cpp(133): error C2059: syntax error : ')'
1>c:\users\beeband\tests.cpp(133): error C2143: syntax error : missing ';' before '{'
1>c:\users\beeband\tests.cpp(133): error C2181: illegal else without matching if
Run Code Online (Sandbox Code Playgroud)

使用BOOST_FOREACH这个的正确方法是什么deque

hmj*_*mjd 7

问题在于,预处理器正在使用它来分离宏参数.

可能的解决方案typedef:

typedef std::pair<int, int> int_pair_t;
std::deque<int_pair_t> chosen;
foreach_( int_pair_t p, chosen )

// Or (as commented by Arne Mertz)
typedef std::deque<std::pair<int, int>> container_t;
container_t chosen;
foreach_(container_t::value_type p, chosen)
Run Code Online (Sandbox Code Playgroud)

在c ++ 11中引入的可能的替换是:


Eri*_*ler 6

作为作者BOOST_FOREACH,我请你停止使用它.这是一个时间已经过去的黑客.请,请使用C++ 11的基于范围的for循环,然后让我们BOOST_FOREACH死掉.