I want a template to select from two types based on some condition. E.g.
struct Base {};
template <typename T1, typename T2>
struct test
{
// e.g. here it should select T1/T2 that is_base_of<Base>
typename select_base<T1, T2>::type m_ValueOfBaseType;
};
Of course to pass condition to the select_base (to make it generic) would be useful, but hard-coded solution is easier and good as well.
Here’s a sample solution that I tried but it always selects T1: http://ideone.com/EnVT8
The question is how to implement the select_base template.
C++14 (and onwards):
In the same vein, you can instead use this:
The difference between these two approaches can be observed when you use them. For example, in the first case if you have to use
::typewhereas in the second, you dont. And if any dependent type involves in the usage of the first approach, you have to usetypenameas well, to assist the compiler. The second approach is free of all such noises and thus superior to the rest of the approaches in this answer.Also, please note that you can write similar type-alias in C++11 as well.
C++11:
C++98:
Conditional is easy enough:
is_base_ofis slightly more complicated, an implementation is available in Boost that I will not reproduce here.Afterwards, see C++11.