mfaieghi
mfaieghi

Reputation: 610

how to use type alias in writing template template functions

I have a template class as follows.

template <class T>
class Point
{
    T x;
    T y;
    using value_type = T;
    Point() {}
    Point(T a, T b)
    {
        x = a;
        y = b;
    }
};

I want to write a function that adds x and y values and return x+y in the type the class is defined. One way is to use a template template as follows:

template <typename T2, template <typename> class T1>
T2 sum(T1<T2> p)
{
    return p.x + p.y;
}

I was wondering is it possible to use type alias defined in the class and avoid writing a template template for the sum function and get similar results? There are similar concerns pointed out in here, but the use of type alias is not discussed there.

Upvotes: 0

Views: 56

Answers (3)

John Zwinck
John Zwinck

Reputation: 249153

You could do it this way, to avoid making sum() accept an overly broad set of types:

template <typename T>
typename Point<T>::value_type sum(const Point<T>& p)
{
    return p.x + p.y;
}

It's const& in case T is large or expensive to copy, and typename is required because value_type is a dependent name (dependent on the type passed as T), so without that the code won't compile as value_type could be a value instead of a type.

A more generic alternative which allows for types T whose operator+ do not result in T would be:

template <typename T>
auto sum(const Point<T>& p)
{
    return p.x + p.y;
}

This does not strictly answer your question of how to use the type alias value_type, but it is probably better code, as it does not place unnecessary restrictions on T.

Upvotes: 1

R Sahu
R Sahu

Reputation: 206607

You sure can.

template <typename T>
typename T::value_type sum(T p)
{
    return p.x + p.y;
}

Upvotes: 3

Collin
Collin

Reputation: 1875

One possibility is to do the following:

template <class T>
T sum(Point<T> p) {
  return p.x + p.y;
}

Upvotes: 2

Related Questions