简体   繁体   English

从C ++中的错误模板实例继承

[英]Inheriting from bad template instantiations in C++

Consider the following code: 考虑以下代码:

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

I have two questions: 我有两个问题:

  1. Can I inherit from Bar<Foo> and override mul() to something meaningful? 我可以继承Bar<Foo>并将mul()重写为有意义的东西吗?

  2. Can I inherit from Bar<Foo> without overriding mul() if I never use mul() anywhere? 如果我从不在任何地方使用mul()是否可以继承Bar<Foo>而不会覆盖mul()

  1. Bar<Foo>::mul() isn't a virtual function, so it cannot be overridden. Bar<Foo>::mul()不是虚函数,因此不能被覆盖。

  2. Yes, if you don't use a template member function then it does not get instantiated and you don't get any errors that would result from instantiating it. 是的,如果不使用模板成员函数,则不会实例化该模板成员函数,并且不会出现任何因实例化模板函数而导致的错误。

You can hide Bar<Foo>::mul() by providing a function of the same signature in a subclass, and because of 2 , Bar<Foo>::mul() won't be instantiated. 您可以通过在子类中提供具有相同签名的函数来隐藏 Bar<Foo>::mul() ,并且由于2Bar<Foo>::mul()不会被实例化。 However this is probably not a good practice. 但是,这可能不是一个好习惯。 Readers are likely to get confused about the hiding vs. overriding, and there's not much benefit to doing this over simply using a different function name and never using mul() , or providing an explicit specialization of Bar for Foo. 读者可能会对隐藏与覆盖感到困惑,并且仅使用不同的函数名而不使用mul()或提供Bar for Foo的显式专业化,这样做没有太大的好处。

  1. sure 当然
  2. sure 当然

Templates are really a kind of smart preprocessor, they're not compiled. 模板实际上是一种智能预处理器,它们未经编译。 If you don't use something, you can write complete (syntactically correct) rubbish, ie you may inherit from 如果您不使用某些东西,则可以编写完整的(在语法上正确的)垃圾,即您可以继承

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

PS since your + operator is used in a const function, it should be declared as const too. PS,因为您的+运算符用于const函数,因此也应将其声明为const。

EDIT : OK, not all compilers support this, here's one that compiles with gcc: 编辑 :好的,不是所有的编译器都支持此功能,这是使用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; }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM