有没有办法自定义编译错误/警告消息
Is there a way to customize the compile error/warning message?
例如,如果我有这样的类:
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的解决方案,您可以使用编译指示。
相关文章:
- 警告处理为错误这里有什么问题
- 将类成员函数作为线程调用到另一个类成员函数时发出警告消息
- GCC 警告和 gcc 错误消息之间的区别
- 修复与mpd_setminalloc相关的警告消息
- 如何避免"'=': truncation of constant value"的警告消息?
- 蓝牙中的警告消息:不支持 TIOCGSERIAL
- QT 信号插槽问题。发出信号,不调用时隙。没有警告,没有错误,没有消息
- 有没有办法自定义编译错误/警告消息
- 我可以在 Xcode 的消息/警告中打印出预处理器值吗?
- 为什么编译器对auto x=a给出不同的警告消息;和auto x(a)
- 将终端上的所有消息和警告打印到文件中
- Bii 发现警告消息与 Apache Xerces 包括
- 如何识别导致Qt警告消息的线路?
- 如何禁用GCC中的#警告消息
- 令人烦恼的C++gcc警告消息
- g++在虚拟析构函数中给出了删除数组的警告消息,这意味着什么
- 具有多重继承的消息映射MFC:如何避免警告C4407和运行时崩溃
- 在使用特定枚举标识符时打印出静态"deprecate"警告消息并附上建议的更正?
- 有关堆栈大小的警告消息
- QtConcurrent::使用MainWindow功能运行,警告消息"QObject::setParent: