Vinod
Vinod

Reputation: 1091

declaring a template function with void return taking a typedef

I have looked at most of the related posts but couldn't find a response that related to my specific usage scenario.

The code is as shown below:

//classA.h file

#include <type_traits>
#include <iostream>

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

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

template<typename T> 
void doSomething(array2As);

template<typename T>
class A{
  public:
  A(T);
  private:
  friend void doSomething(array2As);
  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;
}

template<typename T> void doSomething(array2As a){
  if(is_same<T,int>::value){ auto sz = sizeof(a)/sizeof(int);}
  else{auto sz = sizeof(a)/sizeof(double);}
  static_assert(2 == sz, "Compilation error: array must have exactly 2 elements");
 
  for(auto i=0; i<sizeof(a);++i){
   auto T& = a[i];
   cout << T.elem << endl;
 }

 return;
}

The above code doesn't compile, but you can see what I intend to do. I wish to create a type definition for an array of two instances of the same template class type, and then use that type definition in the declaration of my function template. The function template itself is supposed to be a friend function of the template class type.

I get the compilation error for the following line of code (the compilation doesn't proceed any further due to -Wfatal-errors):

template<typename T> void doSomething(array2As);

and the error is

error: variable or field 'doSomething' declared void

Based on this error, I presume the compiler could not correlate the type definition of arra2As to type T.

So how can make this work?

TIA

P.S:

here is the main.cpp code:

#include "classA.h"

int main (){
 
 array2As a = {A(5),A(7)};
 doSomething(a);
 array2As b = {A(1.2),A(6.3)};
 doSomething(b);

 return 0;
}

Upvotes: 0

Views: 68

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 597490

array2As is a template, so you have to specify its template arguments anywhere that you use it (except in places where the compiler is able to deduce it for you, like in your main()).

For instance:

template<typename T> void doSomething(array2As);

Needs to be:

template<typename T> void doSomething(array2As<T>);

And:

friend doSomething<>(array2As);

Needs to be:

friend doSomething<T>(array2As<T>);

And:

template<typename T> void doSomething<T>(array2As a)

Needs to be:

template<typename T> void doSomething<T>(array2As<T> a)

Upvotes: 0

Related Questions