c++arrayssizetemplate-templates

Deducing the size of an array when a template template parameter is used


A very simple method to find the number of elements in a template array is shown in the following discussion:

How does this function template deduce the size of an array?

I wanted to emulate the same method to get the number of elements in my template template array:

//classA.h

#include <type_traits>
#include <cstddef>
#include <iostream>

using std::is_same;
using std::size_t;
using std::cout;
using std::endl;

template<typename T> class A;
template<typename T>
using array2As = A<T>[2];

template<template<typename T>class A, size_t N>
size_t cal_size(A<T>*&[N]){
 return N;
}

template<typename T>
class A{
  public:
  A(T);
  private:
  A()=delete;
  A(const A&)=delete; 
  A& operator=(const A&)=delete;
  T elem;
};

template<typename T>
A<T>::A(T elem){
  static_assert(is_same<T,int>::value || is_same<T,double>::value, "Compilation error: type must be int or double");
  this->elem = elem;
}


#include "classA.h"

int main (){
 
 array2As<int> a = {A(5),A(7)};
 auto sz = cal_size(a); 
 array2As<double> b = {A(1.2),A(6.3)};
 auto sz = cal_size(b); 

 return 0;
}

For the above code I get the following compiler error:

In file included from main.cpp:1:
classA.h:18:19: error: ‘T’ was not declared in this scope
   18 | size_t cal_size(A<T>*&[N]){
      |                   ^
compilation terminated due to -Wfatal-errors.

Why am I getting this error?


Solution

  • T in template <typename T> class A doesn't introduce T. It is unused. you have to introduce typename T.

    It should be

    template <template <typename> class A, typename T, size_t N>
    size_t cal_size(const A<T>(&)[N]){
         return N;
    }
    

    Demo