Search code examples
c++templates

C++ returning more precise of two template arguments from function?


I'm curious if there's any way to do this in C++. Let's say I have a templated vector class:

template <typename T>
class vector {          
public:
      vector(T a, T b, T c) : x(a), y(b), z(c) {}

      T x,y,z;
};

And then I have a templated addition operator:

template <typename A, typename B> 
vector<A> operator +(const vector<A> &a, const vector<B> &b) { 
   return vector<A>(a.x+b.x, a.y+b.y, a.z+b.z); 
}

I'm curious if it's possible to modify that operator so the result is whichever of the two types A and B is more precise, aside from manually specializing it.

For example:

vector<float>       + vector<double> would produce a vector<double>, 
vector<long double> + vector<float>  would produce a vector<long double>

My guess would be that there's no automatic support for this in C++, but I thought I'd ask.


Solution

  • There isn't any built-in support in the form of a library, but you can accomplish this using the conditional (?:) operator.

    In reply to another answer, Johannes Schaub posted a promote<T, U> template that wraps the logic up quite nicely. With the template, you should be able to write:

    template <typename A, typename B>  
    vector< typename promote<A, B>::type >
    operator+(const vector<A> &a, const vector<B> &b) 
    {     
        return vector< typename promote<A, B>::type >(a.x+b.x, a.y+b.y, a.z+b.z);  
    }