Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

//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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading