Search code examples
c++pointerstemplatesvariadic-templatestype-deduction

Pointer level return type based on template function arguments


For a tensor class I would like to have a template creating functions like

double* mat(int size1);
double** mat(int size1, int size2);
double*** mat(int size1, int size2, int size3);

i.e. the pointer level of the return type depends on the number of inputs. The base case would just be

double* mat(int size1){
  return new double[size1];
}

I thought a variadic template could somehow do the trick

template<typename T, typename... size_args>
T* mat(int size1, size_args... sizes) {
  T* m = new T[size1];
  for(int j = 0; j < size1; j++){
    m[j] = mat(sizes...);
  }
  return m;
}

Deducing the template parameter in m[j] = mat(sizes...); doesn't seem to work though when more than one recursive call would be necessary, as in

auto p = mat<double**>(2,3,4);

but how could I provide the parameter in the recursive call? The correct parameter would be one pointer level below T, that is mat<double**> for T=double***. I feel like I miss something important about templates here.


Solution

  • you cannot declare m and return type as T* since it is not in multiple dimension.

    template<typename T, typename size_type>
    auto mat(size_type size){return new T[size];}
    
    template<typename T, typename size_type, typename... size_types>
    auto mat(size_type size, size_types... sizes){
        using inner_type = decltype(mat<T>(sizes...));
        inner_type* m = new inner_type[size];
        for(int j = 0; j < size; j++){
            m[j] = mat<T>(sizes...);
        }
        return m;
    }