lundi 26 octobre 2015

Non-type parameter templates. Why global and reference?

template<typename Body>
Body solve(Body a, Body b){
    Body zero(0);
    return zero;  
 }
template<typename Body, Body& zero>
   Body solve(Body a, Body b){
   return zero;
}
complex<double> zero(0);
int main(){
 complex<double> c1(1,2);
 complex<double> c2(3,4);    
 solve<complex<double>, zero_complex > (c1,c2);

 return 0;
 }

Hi, I compiled above code and it is OK ( I omitted details here). Now, I noticed that zero must be a global variable and moreover templates must get zero by reference. Otherwise it causes a compilation error. I use c++11.

Please explain me why it must be:

  1. pass by reference
  2. global variable

Thanks in advance.

Aucun commentaire:

Enregistrer un commentaire