首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >带有附加参数的RcppParallel工作人员

带有附加参数的RcppParallel工作人员
EN

Stack Overflow用户
提问于 2020-06-04 07:27:12
回答 1查看 192关注 0票数 0

这是我第一次尝试使用RcppParallel包,我必须使用C++17 (Ubuntu)。

我试图接近开发人员站点的ParallelFor示例,但我需要为worker threshold附加一个(非迭代的)参数。

这是我的当前代码

代码语言:javascript
复制
struct ReplaceWorker : public Worker
{
  // source matrix
  const RMatrix<double> input;

  // destination matrix
  RMatrix<double> output;

  // threshold
  double th;

  // initialize with source and destination
  ReplaceWorker(const NumericMatrix input, NumericMatrix output, double threshold) 
    : input(input), output(output), th(threshold) {}

  // replace function
  template<typename T>
  double replacer(const T &x){
    if(x < th){
      return(0);
    } else {
      return(1);
    }
  }

  // take the square root of the range of elements requested
  void operator()(std::size_t begin, std::size_t end) {
    std::transform(input.begin() + begin, 
                   input.begin() + end, 
                   output.begin() + begin, 
                   replacer);
  }
};

然而,我总是以相同的编译错误告终:

代码语言:javascript
复制
usr/include/c++/7/bits/stl_algo.h:4295:5: note: candidate: template<class _IIter, class _OIter, class _UnaryOperation> _OIter std::transform(_IIter, _IIter, _OIter, _UnaryOperation)
        transform(_InputIterator __first, _InputIterator __last,
        ^~~~~~~~~
   /usr/include/c++/7/bits/stl_algo.h:4295:5: note:   template argument deduction/substitution failed:
   network_edge_strength.cpp:173:28: note:   couldn't deduce template parameter ‘_UnaryOperation’
                       replacer);
                               ^
代码语言:javascript
复制
/usr/include/c++/7/bits/stl_algo.h:4332:5: note: candidate: template<class _IIter1, class _IIter2, class _OIter, class _BinaryOperation> _OIter std::transform(_IIter1, _IIter1, _IIter2, _OIter, _BinaryOperation)
        transform(_InputIterator1 __first1, _InputIterator1 __last1,
        ^~~~~~~~~
   /usr/include/c++/7/bits/stl_algo.h:4332:5: note:   template argument deduction/substitution failed:
   network_edge_strength.cpp:173:28: note:   candidate expects 5 arguments, 4 provided
                       replacer);
                               ^

任何建议,如何修复这个或替代,如何使它运行与所需的threshold参数?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-06-04 07:38:59

replacer是函数模板,而不是函数,这意味着除非使用特定实例化,否则不能将其用作函数对象,否则模板参数推导失败。

此外,作为成员函数,它需要一个隐式对象参数才能被调用。

您可以使用一个泛型lambda表达式来代替:

代码语言:javascript
复制
std::transform(/* [...] */, [this] (const auto& x) { return replacer(x); });

这样,即使replacer被重载或者是一个函数模板,这也是可行的。

或者,完全删除replacer,并直接使用lambda表达式:

代码语言:javascript
复制
std::transform(/* [...] */, [this] (const auto& x) { return x < th ? 0 : 1; });
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62189040

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档