我想使用C ++ 98和g ++编译器将类标记为已弃用,以便在直接使用此类时或者从某个类派生此类时收到警告。
显然,使用__attribute__ ((__deprecated__))
可以在使用类时使用,但不能用于继承。
例如:
#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();
}
我希望收到来自"类Bar:public Foo"的警告,但事实并非如此(使用g ++ 5.2.1进行测试)。
在从弃用的类派生时是否有办法发出警告?
答案 0 :(得分:5)
我能想到解决这个问题的最简单方法是,不是实际标记该类被弃用,而是创建一个被标记为已弃用的类的私有类,并将其实例化为其构造函数中的临时变量。因此,如果实例化派生类,您仍会收到弃用警告。
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
的实例 - 其中一个基本ctors必须在derived
实例的生命周期开始之前运行完成。