c++ - 通过引用的可变模板参数
问题描述
我怎样才能使这个模板函数可变:
template <typename T>
void checkedAlloc(size_t count, T*& x) {
x = new T[count]();
if(nullptr == x){
fprintf(stderr, "Error: not enough memory (%llux%llu bytes).\n\n", count, sizeof(T));
exit(1);
}
}
size_t *A; checkedAlloc(20, A);
以便能够做到:
size_t *A, *B, *C; checkedAlloc(20, A, B, C);
?
解决方案:
C++17:丹妮
template <typename ...T>
void checkedAllocV(size_t count, T*& ...x) {
((checkedAlloc(count, x)), ...);
}
C++14:mch
void checkedAlloc(size_t count) {}
template <typename T, class ... Ts>
void checkedAlloc(size_t count, T*& x, Ts&& ...args) {
try { x = new T[count](); }
catch (const std::bad_alloc) {
fprintf(stderr, "Error allocating memory (%zux%zu bytes).\n", count, sizeof(T));
exit(1);
}
checkedAlloc(count, args...);
}
解决方案
template <typename ...T>
void checkedAllocV(size_t count, T*& ...x) {
((checkedAlloc(count, x)), ...);
}
推荐阅读
- reactjs - 带有 esc-bluetooth-printer 插件的 react-native 找不到插件功能
- mitmproxy - 如何在“def request()”中直接返回响应
- javascript - 访问使用 Promise 创建的对象属性时出现问题
- javascript - 为什么我的 React Native 类组件返回错误:this.setState is not a function?
- linux - 使用 bash 脚本的生肖计算器
- javascript - 如何使用javascript从函数参数返回值?
- python - 如何在 Django 中显示从模型到模板的元组字段?
- vba - 我的代码在单元格(i,1)上运行良好,但在单元格(i,2)上出现类型不匹配错误。衷心欢迎您的建议
- angular-material - Angular Material 组件不会在通用应用程序中呈现
- visual-studio - 使用 cmake 构建的可执行文件找不到共享库