Choosing a parameter type based on a template parameter

I am writing a C ++ 11 template function void foo(T, U)using two parameters:

The first parameter, which can be either type A1 or 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, is there a way to write this function that requires only one template parameter?

Something along the line

template class <T>
void foo(T t, std::conditional<A1* tmp = dynamic_cast<T*>(&t), A2, B2>::type);

may work, but its ugly and needs RTTI.

Is there a good way to achieve this?

+4
source share
1 answer

Yes, this can be done without RTTI. how best to do this depends on how A1 and A2 are connected.

, typedef A1

class A1
{
     using RelatedType = A2;
}

B1 B2

template class <T>
void foo(T t, T::RelatedType t2);

A1,

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
}

( As, Bs)

template<>
struct TypeRelation<A1>
{
     using RelatedType = A2;
}

template class <T>
void foo(T t, typename TypeRelation<T>::RelatedType t2);

++ 11s decltype , .

+1

All Articles