c++ - 重载运算符 & 继承 & 模板(一个强大的组合)

标签 c++ templates inheritance operator-overloading

大家好。

我正在使用 Boost Units 库编写一些代码,但遇到了问题。

我已经设法从 Boost 代码中抽象出问题,这样您就不会浏览大量的 Boost 模板元编程。虽然我敢肯定,如果您有这方面的经验,它可能会有所帮助。这是复制品:

class Base{};
class Derived : public Base
{
public:
  Derived(){}
  Derived(const Base &){}
};

class Q {};
class U
{
public:
  template< typename Y >
  Q operator * (Y)
  {
    Q r;
    return r;
  }
};

Base operator * (U, const Base &)
{
  Base r;
  return r;
}

int main(int argc, char **argv)
{
  Base myBase;
  U myU;
  Base myOtherBase = myU * myBase;
  Derived myDerived;
  Derived myOtherDerived =  myU * myDerived;
  return 0;
}

所以问题(具体)如下:myU * myBase使用 operator * (U, const Base &)并返回 Base 的类型,到目前为止一切都很好。鉴于 myU * myDerived坚持使用广义U::operator * (Y)因此返回 Q ,不好,因为我想要一个 Base再次。

现在,除 Base 以外的所有类和 Derived是 boost 库类,所以我不能修改 U 的成员。我如何“击败”U::operator * (Y)对于重载/模板推导/实例化,在这种情况下,以一种优雅且“一劳永逸”的方式。

我正在使用 MSVC++ 2008,以防它与任何人相关。

编辑:在答案中添加了一个可能(很可能)的解决方案

最佳答案

使用以下应该可以解决您的问题

Base myOtherDerived =  myU * (Base&)myDerived;
// or
Base myOtherDerived =  myU * static_cast<Base&>(myDerived);

代替

Derived myOtherDerived =  myU * myDerived;

虽然这不是我们所说的“干净的解决方案”。 我正在努力寻找更好的方法。

关于c++ - 重载运算符 & 继承 & 模板(一个强大的组合),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5999620/

相关文章:

c++ - 基类不完整的继承

css - 模板不加载静态文件

templates - <h2> 和 img 在一行中

java - 组合语法对 Java 有用吗?

c++ - 由于继承而返回拷贝的堆栈?

给定类型列表的 C++ 专用模板类

c++ - GlobalMemoryStatusEx 线程安全吗?

c++ - 在发出等待条件变量信号后,线程何时获取锁?什么决定了它?

c++ - 我自己的 COM 组件上未注册类 (0x80040154)

C++ Protobuf 未定义对构造函数/析构函数的引用