C++ Logo

std-proposals

Advanced search

Explicit alias template specialization

From: Nicolas Weidmann <n.weidmann_at_[hidden]>
Date: Fri, 19 Nov 2021 14:48:14 +0100
Hello,

Currently most templates can be fully specialized, however, alias templates cannot.
 
As the following examples illustrate, the problem alias templates specialization would solve can currently be mimicked using alias traits.
 
But adding alias templates specialization would render to code more straightforward and readable:
 
The first example uses a default alias template followed by specializations.
The second example ‘deletes’ the default alias template, only allowing for specialized versions.
 
The first example achieved using traits:
 
///////////////////////////////////////////////////////////////
 
template<typename T> struct AliasTrait {
   using type = std::set<T>;
};
 
template<> struct AliasTrait<int> {
   using type = std::vector<int>;
};
 
template<> struct AliasTrait<double> {
   using type = std::list<double>;
};
 
template<typename T> void foo()
{
   typename AliasTrait<T>::type values;
}
 
The first example achieved using alias template specialization:
 
///////////////////////////////////////////////////////////////
 
template<typename> using alias = std::set<T>;
 
template<> using alias<int> = std::vector<int>;
template<> using alias<double> = std::list<double>;
 
template<typename T> void foo()
{
   alias<T> values;
}
 
The second example achieved using traits:
 
///////////////////////////////////////////////////////////////
 
template<typename> structNoDefaultAliasTrait;
 
template<> struct NoDefaultAliasTrait<int> {
   using type = std::vector<int>;
};
 
template<> structNoDefaultAliasTrait<double> {
   using type = std::list<double>;
};
 
template<typename T> void bar()
{
   typename NoDefaultAliasTrait<T>::typevalues;
}
 
The second example achieved using alias template specialization and introducing ‘deletion’ of the generic alias template:
 
///////////////////////////////////////////////////////////////
 
template<typename> using no_default_alias= delete;
 
template<> using no_default_alias<int> = std::vector<int>;
template<> using no_default_alias<double> = std::list<double>;
 
template<typename T> void bar()
{
   no_default_alias<T> values;
}
 
Regards,
 
Nicolas




Sent from my iPhone

Received on 2021-11-19 07:48:19