1

之前在这里提出过相关问题,但我还是没有找到满意的答案,所以我会尽力解释我的问题,希望有人能赐教。

我目前正在使用 boost::multi_array 编写一些代码,并且代码本身也是维度无关的。我需要遍历存储在 multi_array 中的所有元素并对它们做一些事情。我希望以类似 STL 的方式执行此操作:

for_each(begin(array), end(array), function);

或类似的东西。其他问题向我指出了 boost 页面本身的一个示例:

for_each 示例
for_each 实现

这或多或少正是我想要的。当人们试图简单地将这段代码导入一个更大的程序时,问题就来了。人们自然希望将函数本身包装在某个命名空间中,并使用例如 C++ 函数作为函数对象。执行这两个中的任何一个都会为编译器创建模板查找问题。

有谁知道我如何解决模板查找问题,或者另一种方法(希望同样漂亮)?

附加信息:

将 for_each 定义包装在命名空间中时出现编译错误

./for_each.hpp:28:3: error: call to function 'for_each' that is neither visible in the template definition nor found by
argument-dependent lookup
  for_each(type_dispatch,A.begin(),A.end(),xform);
  ^
./for_each.hpp:41:5: note: in instantiation of function template specialization
'boost_utilites::for_each<boost::detail::multi_array::sub_array<double, 1>,
      double, times_five>' requested here
    for_each(type_dispatch,*begin,xform);
    ^
./for_each.hpp:50:3: note: in instantiation of function template specialization 'boost_utilites::for_each<double,
      boost::detail::multi_array::array_iterator<double, double *, mpl_::size_t<2>, boost::detail::multi_array::sub_array<double,
1>,
      boost::random_access_traversal_tag>, times_five>' requested here
  for_each(boost::type<typename Array::element>(),A.begin(),A.end(),xform);
  ^
foreach_test.cpp:46:19: note: in instantiation of function template specialization
'boost_utilites::for_each<boost::multi_array<double, 2,
      std::allocator<double> >, times_five>' requested here
  boost_utilites::for_each(A,times_five());
                  ^
./for_each.hpp:37:6: note: 'for_each' should be declared prior to the call site or in an associated namespace of one of its
arguments
void for_each (const boost::type<Element>& type_dispatch,
     ^
1 error generated.

在示例中使用 std::function 对象而不是 times_five 对象时,会得到基本相同的编译错误。

使用 clang 版本 3.4-1ubuntu3 编译。

4

1 回答 1

2

只是

std::for_each(array.data(), array.data() + array.num_elements(), function);

要使其与期望随机访问范围的函数一起工作(使用.begin(),.end().size()),请使用

auto elements = boost::make_iterator_range(array.data(), array.data() + array.num_elements();

// e.g.
for (auto& element : elements) {

    ...
}

我个人喜欢将它与generate_nfill_n等一起使用:

std::for_each(array.data(), array.num_elements(), 0);

参考文档

  • element* data();
  • const element* data() const;

    这将返回一个指向包含数组数据的连续块的开头的指针。如果数组的所有维度都以 0 为索引并按升序存储,则相当于 origin()。请注意, const_multi_array_ref 仅提供此函数的 const 版本。

  • size_type a.num_elements()

    这将返回数组中包含的元素数。它等价于以下代码:

    std::accumulate(a.shape(),a.shape+a.num_dimensions(), 
               size_type(1),std::multiplies<size_type>());> 
    
于 2015-03-26T15:12:31.047 回答