从已弃用的继承 class

Inheritance from deprecated class

我想使用 C++98 和 g++ 编译器将 class 标记为已弃用,以便在直接使用此 class 或有人从此 class.

显然,使用 __attribute__ ((__deprecated__)) 在使用 class 时有效,但不适用于继承。

例如:

#if defined(__GNUC__)
# define DEPRECATED __attribute__ ((__deprecated__))
#else
# define DEPRECATED
#endif


class DEPRECATED Foo
{
public:
    explicit Foo(int foo) : m_foo(foo) {}
    virtual ~Foo() {}

    virtual int get() { return m_foo; }

private:
    int m_foo;
};


class Bar : public Foo // This declaration does not produce a compiler
                       // warning.
{
public:
    explicit Bar(int bar) : Foo(bar), m_bar(bar) {}
    virtual ~Bar() {}

    virtual int get() { return m_bar; }

private:
    int m_bar;
};

int main(int argc, char *argv[])
{
    Foo f(0); // This declaration produces a warning.
    Bar b(0); // This declaration does not produce a warning.
    return b.get();
}

我希望收到来自 "class Bar : public Foo" 的警告,但事实并非如此(使用 g++ 5.2.1 测试)。

有没有办法在派生自已弃用的 class 时发出警告?

我认为解决此问题的最简单方法是,不是实际标记 class 已弃用,而是将标记为已弃用的 class 设为私有 class,并且它在其构造函数中将其实例化为临时变量。因此,如果您实例化派生的 class.

,您仍然会收到弃用警告
class base {
  class DEPRECATED deprecator {};
public:
  base() {
    deprecator issue_warning;
    (void) issue_warning; // this line is no-op to silence unused variable warning for local variable
  }
};

class derived : public base {
public:
  derived()
    : base()
  {
    // I am also deprecated, because I called the ctor for base
    // which instantiates a deprecated class
  }
};

如果 base 有许多不同的构造函数,这可能实现起来更复杂,但这至少给出了思路。通常,无论何时构造 derived 的实例,都必须构造 base 的实例——其中一个基本构造函数必须 运行 在 derived 实例的生命周期之前完成可以开始了。