将boostforeach与本身就是模板的项目一起使用

using boost foreach with items that are themselves templates

本文关键字:项目 一起 boostforeach      更新时间:2023-10-16

我有一个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 )
  {
     ... 
  }

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

warning C4002: too many actual parameters for macro 'BOOST_FOREACH'
1>c:usersbeebandtests.cpp(133): error C2143: syntax error : missing ')' before '>'
1>c:usersbeebandtests.cpp(133): error C2059: syntax error : '>'
1>c:usersbeebandtests.cpp(133): error C2059: syntax error : ')'
1>c:usersbeebandtests.cpp(133): error C2143: syntax error : missing ';' before '{'
1>c:usersbeebandtests.cpp(133): error C2181: illegal else without matching if

BOOST_FOREACH与此deque一起使用的正确方法是什么?

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

使用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)

可能的替代品,都是在c++11中引入的,有:

  • 环路范围:

    for (auto& : chosen)
    {
    }
    
  • lambdas:

    std::for_each(std::begin(chosen),
                  std::end(chosen)
                  [](std::pair<int, int>& p)
                  {
                  });
    

作为BOOST_FOREACH的作者,我请求您停止使用它。这是一个时间来了又去的黑客。请,请,请使用C++11的范围基数进行循环,并让BOOST_FOREACH死亡。

Boosts foreach,这意味着它由预处理器处理。预处理器非常简单,不能处理带有逗号的符号,因为它被用作宏参数分隔符。