Iter Ator
Iter Ator

Reputation: 9299

How is it possible to use the type of a template parameter's member?

My function looks like this:

template<typename T, typename U>
T myfunc(T a, T b) {
    // the type of a.data and b.data is U
    // ...
}

An example of type T and U looks like this:

class ExampleT {
public:
    int data;
};

Where T is the class, which has a member named data. And the type of data is U

My function has to be called at the moment with two type parameters:

myfunc<T, U>(...);

But the second type parameter (U) is the type of the data variable inside the first type (T). Is it possible, to remove the U from the template, and detect it for example using decltype?

All of the latest C++14 features may be used.

Upvotes: 2

Views: 75

Answers (1)

WhiZTiM
WhiZTiM

Reputation: 21576

You could deduce it as a default template parameter:

template<typename T, typename U = decltype(T::data)>
T myfunc(T a, T b) {
    // the type of a.data and b.data is U
    // ...
}

Demo; Or within the function body:

template<typename T>
T myfunc(T a, T b) {
    using U = decltype(T::data);
    // ...
}

Or using a local typedef, as suggested by Columbo

struct ExampleT {
    using Type = int;
    Type data;
};

template<typename T, typename U = typename T::Type>
T myfunc(T a, T b) {
    // ...
}

Upvotes: 6

Related Questions