I have a class template for which I want to introduce several template specializations. Those template specializations identical to some existing type. Conceptually I would
Yes you can, by using type aliases:
template using Common = TypeZ;
See the link for more examples of what is possible. using
can be used anywhere typedef
can be used, plus in template aliases like the above, so I recommend using using
over typedef
everywhere you write C++11.
If you need a more complicated mapping, you can use some simple template metaprogramming using std::enable_if or std::conditional combined with std::is_same. For example, if you need to specialize for 3 types only, use this:
#include
class Type1 {};
class Type2 {};
class Type3 {};
class Type4 {};
class TypeZ {};
// Implementation 1
template
constexpr bool is_Type123_func()
{
return std::is_same() || std::is_same() || std::is_same();
}
template
using Common_byfunc = typename std::conditional(), TypeZ, T>::type;
static_assert(std::is_same, TypeZ>(), "");
static_assert(std::is_same, TypeZ>(), "");
static_assert(std::is_same, TypeZ>(), "");
static_assert(!std::is_same, TypeZ>(), "");
// Implementation 2
template
struct is_Type123 : public std::conditional() || std::is_same() || std::is_same(), std::true_type, std::false_type>::type {};
template
using Common = typename std::conditional::value, TypeZ, T>::type;
static_assert(std::is_same, TypeZ>(), "");
static_assert(std::is_same, TypeZ>(), "");
static_assert(std::is_same, TypeZ>(), "");
static_assert(!std::is_same, TypeZ>(), "");
Both implementations are equivalent up to a name and the fact you have to use a function call operator ()
or the member accessor ::value
in the std::conditional
.