首页 > 解决方案 > 通过引用的可变模板参数

问题描述

我怎样才能使这个模板函数可变:

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++14mch

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...);
}

标签: c++

解决方案


template <typename ...T>
void checkedAllocV(size_t count, T*& ...x) {
    ((checkedAlloc(count, x)), ...);
}

推荐阅读