samedi 8 août 2020

Apply std::conj in template function if template argument is complex

TL;DR Let's say I have a function with a template argument T that takes a std::vector<T>& as input (see below), I want to conjugate this vector, if T is a complex type. How can I do that ?

What I have tried Following https://stackoverflow.com/a/30737105/5913047, I know I can check if a type is complex with

template<class T> struct is_complex : std::false_type {};
template<class T> struct is_complex<std::complex<T>> : std::true_type {};

So I tried:

template<typename T>
void MyFunction(std::vector<T>& MyVector){
    // do something
    if (is_complex<T>()){
       std::transform(MyVector.begin(), MyVector.end(), MyVector.begin(),[](T&c){return std::conj(c););
    }
}

but then, if I use this function with a non complex type, the compiler says that conj is not defined for non complex type. Is there some design to do what I want ?

Aucun commentaire:

Enregistrer un commentaire