gpt4 book ai didi

c++ - 如何在 C++ operator() 中专门化调用模板?

转载 作者:行者123 更新时间:2023-11-30 04:59:09 26 4
gpt4 key购买 nike

考虑这段代码:

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);
}

这不会编译,因为在 f() 中, pp不知道要使用哪个操作。我试过 pp<add1_op>(&f, 0, f);但是 clang 说 pp 没有命名模板。调用 pp 的正确方法是什么?带有模板参数的 operator()? (我希望它是一个模板 arg,所以它内联而不是通过函数指针调用。)或者如果这行不通,是否有一种有效的替代方法来完成我想要做的事情?我想要各种PixelProcess* , 和 *_op方法并有效地混合它们。

最佳答案

更简单的方法是在参数中传递仿函数:

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);
}

关于c++ - 如何在 C++ operator() 中专门化调用模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51368946/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com