GaryO
GaryO

Reputation: 6338

How to specialize call template in c++ operator()?

Consider this code:

struct PixelProcessChannelwise {
  template<class Op, typename... Args>
  void operator()(float *dest, int process_nchannels, Args... srcs) const {
    for (int ch = 0; ch < process_nchannels; ch++) {
      Op{}(dest, srcs[ch]...);
    }
  }
};

struct add1_op {
  void operator()(float& dst, float x) const {
    dst = x + 1;
  }
  typedef PixelProcessChannelwise processor;
};

void f() {
  float f = 1.0;
  auto pp = PixelProcessChannelwise();
  pp(f, 0, &f);
}

This doesn't compile because in f(), pp doesn't know which op to use. I tried pp<add1_op>(&f, 0, f); but clang says pp does not name a template. What's the right way to invoke pp operator() with a template arg? (I want it to be a template arg so it inlines rather than calling through a function pointer.) Or if this can't work, is there an efficient alternative to do what I'm after? I want to have various PixelProcess*, and *_op methods and mix them efficiently.

Upvotes: 1

Views: 109

Answers (1)

Jarod42
Jarod42

Reputation: 217145

Simpler would be to pass functor in argument:

struct PixelProcessChannelwise {
  template<class Op, typename... Args>
  void operator()(Op&& op, float &dest, int process_nchannels, Args... srcs) const {
    for (int ch = 0; ch != process_nchannels; ch++) {
      std::forward(op)(dest, srcs[ch]...);
    }
  }
};

struct add1_op {
  void operator()(float& dst, float x) const {
    dst = x + 1;
  }
  typedef PixelProcessChannelwise processor;
};

void f() {
    float f = 1.0f;
    auto pp = PixelProcessChannelwise();
    pp(add1_op{}, f, 0, &f);
}

Upvotes: 1

Related Questions