mardi 28 août 2018

std::get like (partial) template specialization

I have class for complex numbers:

template<typename T>
struct Complex{
    T r;
    T i;
};

I decided to add function similar to std::get:

template<int X, typename T>
T get(const Complex<T> &a){
   switch(X){
       case 0: return a.r;
       case 1: return a.i;
   }
}

This works OK. Also I know the compiler can optimize it away.

Then I decided to rewrite it in different way:

template<int X,typename T>
T get(const Complex<T> &a);

template<typename T>
constexpr T get<0, T>(const Complex<T> &a){
    return a.r;
}

template<typename T>
constexpr T get<1, T>(const Complex<T> &a){
    return a.i;
}

However this does not compile and I am curious how correct implementation will be?

I tried to check how std::get is made, but I was unable to find anything that was "readable".

Aucun commentaire:

Enregistrer un commentaire