考虑以下代码:
struct Foo
{
Foo operator+(const Foo &rhs) const;
// notice lack of: Foo operator*(const Foo &rhs) const;
};
template <class T>
struct Bar
{
T x, y;
T add() const { return x + y; }
T mul() const { return x * y; }
};
我有两个问题:
我可以继承自
Bar<Foo>
吗?并覆盖mul()
做一些有意义的事情?我可以继承自
Bar<Foo>
吗?不覆盖mul()
如果我从不使用mul()
哪里?
最佳答案
- 当然
- 当然
模板实际上是一种智能预处理器,它们不是经过编译的。如果你不使用某些东西,你可以写出完整的(语法正确的)垃圾,即你可以继承自
template <class T>
struct Bar
{
T x, y;
T add() const { return x + y; }
T mul() const { return x.who cares what-s in here; }
};
附言由于您的 + 运算符在 const 函数中使用,因此它也应声明为 const。
编辑:好的,不是所有的编译器都支持这个,下面是一个用 gcc 编译的编译器:
template <class T>
struct Bar
{
T x, y;
T add() const { return x + y; }
T mul() const { T::was_brillig & T::he::slith(y.toves).WTF?!0:-0; }
};
关于c++ - 从 C++ 中的错误模板实例化继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11263635/