c++ - 将 boost foreach 与本身就是模板的项目一起使用

标签 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 )
  {
     ... 
  }

但是当我编译它时(在 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

正确的使用方法是什么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 中引入的可能的替代品是:

  • range-for循环:

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

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

关于c++ - 将 boost foreach 与本身就是模板的项目一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17467683/

相关文章:

c++ - 多个数组中的排序算法;二进制搜索功能

c++ - 如何在结构中存储二进制文件数据?

c++ - Qt moc 文件没有扩展 #include "foo.h"之前定义的宏

c++ - RAII 类的通用命名约定是什么?

c++ - 使用 boost 库编译 C++ 代码时出现问题

c++ - 在遍历多个集合时写回迭代器

c++ - 这是 boost 条件变量的正确使用吗?

c++ - 我应该使用 const 引用还是 boost::shared_ptr?

c++ - 为什么 BOOST_FOREACH 不完全等同于手工编码?

c++ - 无法让 BOOST_FOREACH 与我的自定义类一起工作