c – 将运算符作为函数模板参数传递

前端之家收集整理的这篇文章主要介绍了c – 将运算符作为函数模板参数传递前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我必须为我制作的一些非常复杂的对象重载基本的算术运算符.到目前为止,我已经成功实现了operator *;现在我需要运算符等.运算符*的代码非常大,但运算符*和运算符之间的唯一区别将是我在一些复数上使用而不是*的一行.这一行将在一个被多次调用的循环内部,所以我希望它有效,这似乎意味着没有函数指针. (如我错了请纠正我.)

这似乎是模板的完美用法.但我对正确的语法感到茫然.我在ComplicatedObject类定义中考虑这样的事情:

template <typename ComplexBinaryOp>
ComplicatedObject BinaryOp(const ComplicatedObject& B) const {
  // Do lots of stuff
  for(unsigned int i=0; i<OneBazillion; ++i) {
    // Here,the f[i] are std::complex<double>'s:
    C.f[i] = ComplexBinaryOp(f[i],B.f[i]);
  }
  // Do some more stuff
  return C;
}

inline ComplicatedObject operator*(const ComplicatedObject& B) const {
  return BinaryOp<std::complex::operator*>(B);
}

inline ComplicatedObject operator+(const ComplicatedObject& B) const {
  return BinaryOp<std::complex::operator+>(B);
}

这个问题是相关的:“function passed as template argument”.但作为模板参数传递的函数不是运算符.

我已经用我能想到的各种方式摆弄了语法,但编译器总是抱怨语法错误.我该怎么做?

编辑:

为清楚起见,我在上面的代码中包含了完整的解决方案,以及人们可能需要的其他概括:

template <typename ComplexBinaryOp>
ComplicatedObject BinaryOp(const ComplicatedObject& B) const {
  // Do lots of stuff
  for(unsigned int i=0; i<OneBazillion; ++i) {
    // Here,the f[i] are std::complex<double>'s:
    C.f[i] = ComplexBinaryOp()(f[i],B.f[i]); // Note extra ()'s
  }
  // Do some more stuff
  return C;
}

inline ComplicatedObject operator+(const ComplicatedObject& B) const {
  return BinaryOp<std::plus<std::complex<double> > >(B);
}

inline ComplicatedObject operator-(const ComplicatedObject& B) const {
  return BinaryOp<std::minus<std::complex<double> > >(B);
}

inline ComplicatedObject operator*(const ComplicatedObject& B) const {
  return BinaryOp<std::multiplies<std::complex<double> > >(B);
}

inline ComplicatedObject operator/(const ComplicatedObject& B) const {
  return BinaryOp<std::divides<std::complex<double> > >(B);
}

解决方法

我认为std :: plus< std :: complex>和std :: multiplies< std :: complex>你正在寻找什么,但我不是100%肯定我理解你的问题(你的课程中的代码片段是你没有向我们展示的吗?)
原文链接:https://www.f2er.com/c/118708.html

猜你在找的C&C++相关文章