c++ - 如何在带有初始化程序的构造函数中使用 vprintf/cstdarg 功能?
问题描述
我想创建一个MyException
扩展类std::runtime_error
,并带有具有printf
语法的异常消息。我想这样使用它:
int main()
{
int index = -1;
if (index < 0)
throw MyException("Bad index %d", index);
}
我该如何编写构造函数MyException
?
class MyException: public std::runtime_error
{
MyException(const char* format ...):
runtime_error(what?)
};
我假设我必须在某个地方va_list
打电话vprintf
,但我怎样才能将它与初始化语法结合起来呢?
解决方案
使用可变参数模板sprintf
:
class MyException: public std::runtime_error {
char buf[200]; // One issue: what initial size of that?
template<class ... Args>
char* helper(Args ... args)
{
sprintf(buf, args...);
return buf;
}
public:
template<class ... Args>
MyException(Args ... args):
std::runtime_error( helper(args...) )
{
}
};
推荐阅读
- c++ - 查找最大元素的索引
- process - 使用管道的 IPC,ABC
- python - 如何使用 Tkinter filedialog 将文件上传到服务器
- javascript - Javascript - 使用 map 重构(if 语句,意大利面条代码)
- vue.js - Vuetify 通过 prepend-item 事件更新选择输入值
- materialized-views - 无法使用“提交时快速刷新”在远程数据库上创建物化视图
- html - 粘性div卡在行中
- ipython - 如何使用 start_ipython() 配置 IPython 会话?
- excel - 连接到 Office 2016 时数据库提供程序名称不存在
- javascript - 如何使用 React 选择兄弟元素?