Reputation: 4275
I am writing a C++11 template function void foo(T, U)
taking two parameters:
The first parameter which can either be of type A1 or of type B1. If the first parameter is of type A1, the second parameter is of type A2; If the first parameter is of type B1, the second parameter is of type B2;
Since the second parameter depends on the first one, is there a way of writing this function needing only one template parameter?
Something along the line of
template class <T>
void foo(T t, std::conditional<A1* tmp = dynamic_cast<T*>(&t), A2, B2>::type);
might work, but its ugly and needs RTTI.
Is there a good way of achieving this?
Upvotes: 4
Views: 84
Reputation: 1266
Yes, it can be done without RTTI. how best to do it depends on how A1 and A2 are related.
If you control the classes you can add a using or typedef into A1
class A1
{
using RelatedType = A2;
}
and similar for B1 and B2
then
template class <T>
void foo(T t, T::RelatedType t2);
If you cant edit A1 you can create a type trait
template<typename T>
struct TypeRelation // would have a better name if we knew why they were related
{
// can put a default related type here if you want
}
and then use template specialization (example for As, but need similar for Bs)
template<>
struct TypeRelation<A1>
{
using RelatedType = A2;
}
and then the declaration becomes
template class <T>
void foo(T t, typename TypeRelation<T>::RelatedType t2);
C++11s decltype may also be suitable depending on how the classes are related.
Upvotes: 1