有没有办法自定义编译错误/警告消息

Is there a way to customize the compile error/warning message?

本文关键字:警告 消息 错误 编译 自定义 有没有      更新时间:2023-10-16

例如,如果我有这样的类:

class Widget {
public:
  virtual void Init(); // In this function, call some virtual function
                       // to construct the object
  void Paint();        // Deprecated, use paintWidget instead
  void PaintWidget();  // A new implementation of paint
  ...                  // Other stuff, including a virtual function
                       // which need to be called to construct the object
}

Widget的构造需要虚函数调用(这就是我编写Widget::Init()的原因)。有没有办法对Widget::Init()进行约束,以便在使用对象之前必须调用它,并在用户违反约束时引发错误?另一个问题是为已弃用的方法创建自定义警告消息。使用上面的代码,如果我类的用户调用Widget::paint(),我如何告诉他们使用 Widget::paintWidget() 而不是不推荐使用的 Widget::paint(),并告诉他们使用已弃用的后果?谢谢。

您问题的第 1 部分:

不,没有使用私有方法提供自定义消息的好方法。我要做的是确保您只有一个转发到私有实现的公共 API。这可以通过一些疙瘩图案或创建立面来完成。

由于您没有指定某人获取小部件的方式,因此我目前假设是单例。

class Widget {
public:
    Widget() : _impl(getHoldOfPrivateWidgetViaSingleton())
    {
         _impl.init();
    }
    // ...
private:
    PrivateWidget &_impl;
};
// Note: rename of the Widget in your example
class PrivateWidget {
private:
    friend class Widget;
    PrivateWidget();
    // ...
};

这样做的缺点是你将不得不编写一些/大量的转发代码。

问题的第 2 部分:

class Widget {
public:
  void Init();
  [[deprecated("use paintWidget instead")]] void Paint();
  void PaintWidget(); // A new implementation of paint
  ...
private:
  Widget();
  ...
}

请注意,如果您无权访问启用了 C++17 的新式编译器,则可能需要签出编译器特定的属性。

您可以使用 #warning 指令,大多数广泛使用的编译器(GCC,VC,Intels和Mac)都支持 #warning 消息。

#warning "this is deprecated, use the Init() method instead"

一个好的做法是不仅显示警告(人们可以忽略),而且使用 #error 指令(这是非常标准的)使编译失败:

#  error "this method is forbidden and private"

作为特定于Visual Studio的解决方案,您可以使用编译指示