Reputation: 9299
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
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