[英]Variadic template arguments by reference
How can I make this template function variadic:如何制作此模板 function 可变参数:
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);
so as to be able to do:以便能够做到:
size_t *A, *B, *C; checkedAlloc(20, A, B, C);
? ?
Solutions:解决方案:
template <typename ...T>
void checkedAllocV(size_t count, T*& ...x) {
((checkedAlloc(count, x)), ...);
}
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)), ...);
}
The C++14 version: It handles 1 parameter and calls the function with 1 less parameter. C++14 版本:它处理 1 个参数,并以少 1 个参数调用 function。 Termination function, when there is only
count
left to break the recursion.终止 function,当只剩下
count
来中断递归时。
void checkedAlloc(size_t count) {}
template <typename T, class ... Ts>
void checkedAlloc(size_t count, T*& x, Ts&& ...args) {
x = new T[count]();
if(nullptr == x){
fprintf(stderr, "Error: not enough memory (%zux%zu bytes).\n\n", count, sizeof(T));
exit(1);
}
checkedAlloc(count, args...);
}
https://godbolt.org/z/16jjsb https://godbolt.org/z/16jjsb
Let's go through the call graph for this main function:让我们通过这个主要 function 的调用图 go:
int main()
{
MyClass *A;
int *B;
float *C;
checkedAlloc(20, A, B, C);
delete[] A;
delete[] B;
delete[] C;
}
checkAlloc
gets called with 4 parameters (20, A, B, C). checkAlloc
使用 4 个参数(20、A、B、C)调用。
This call allocs 20 elements of type of A and calls checkAlloc
with 3 parameters (20, B, C).此调用分配了 20 个 A 类型的元素,并使用 3 个参数(20、B、C)调用
checkAlloc
。
This call allocs 20 elements of type of B and calls checkAlloc
with 2 parameters (20, C).此调用分配了 20 个 B 类型的元素,并使用 2 个参数 (20, C) 调用
checkAlloc
。
This call allocs 20 elements of type of C and calls checkAlloc
with 1 parameter (20).此调用分配 20 个类型为 C 的元素,并使用 1 个参数 (20) 调用
checkAlloc
。
This call ends up in the non template function in line 1 and does nothing.此调用在第 1 行的非模板 function 中结束,并且什么也不做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.