vendredi 25 août 2017

Specialize a c++ class member function respect to a template class

That's my problem:

I've a class cc and I want to specialize this a class member method respect to another template class (with a template argument). An example:

#include <iostream>
#include <string>
#include <complex>

template<class T>
class cc {
    public:

    void foo() ;

    T v ;
};

template<class T> // OK, generic definition of foo()
void cc<T>::foo() {
    std::cout << v << std::endl ;
}

////////////////////////////////////////////////////////////////////
// ERROR! can not accept the the specialization respect to a 
// complex<TT> with a template argument.
template<class TT> 
void cc< std::complex<TT> >::foo() {
    std::cout << "complex t " << v << std::endl ;
}
////////////////////////////////////////////////////////////////////


template<> // OK! specialization respect to a complex<double>
void cc< std::complex<double> >::foo() {
    std::cout << "complex " << v << std::endl ;
}


template<> // OK!
void cc< double >::foo() {
    std::cout << "double: " << v << std::endl ;
}

int main()
{
  cc< std::complex<double> > r ;
  cc<double> r2 ;

  r.foo() ;
  r2.foo() ;
}

In c++ complex is a template type, so I want to write a member function that works with every complex< type > where type is any template type. It is possible?

Aucun commentaire:

Enregistrer un commentaire