是否可以创建模板别名

Is it possible to create a template alias?

本文关键字:别名 建模 创建 是否      更新时间:2023-10-16

请考虑以下代码:

template< template< typename ... > class ... Ts >
struct unite
{
    template< typename ... T >
    struct type
        : Ts< T ... > ...
    { };
};
// This does not work as ::type does not name a type, but a template:
// template< template< typename ... > class ... Ts >
// using unite_t = typename unite< Ts ... >::type;
template< typename > struct debug_none {};
template< typename > struct debug_cout {};
template< typename ... > struct raise_demangled {};
template< typename ... > struct raise_specialized {};
template< typename, typename = int > struct match_default {};
template< template< typename ... > class Control >
void f()
{}
int main()
{
    f< unite< debug_none, raise_demangled, match_default >::type >();
    // Is there any way to create something like unite_t which works like this:
    // f< unite_t< debug_none, raise_demangled, match_default > >();
}

现场示例

问:有没有办法创建某种类似于类型别名的"模板别名"?(请参阅上例中的unite_t

不,你不能。

using可以"返回"类型或变量。 它不能"返回"template. 其他地方没有类似的机制。

你可以做一些模糊有用的事情,通过采用约定,即所有模板都不是模板,而是里面有template<?>using apply=?;别名的类(当我们这样做时,常量是std::integral_constants<T,?>,指针是pointer_constant<T*,?>)。

现在一切都是一堂课。 template 变成了只是类(带有::apply<?...> .

将一

堆类型应用于此类模板将通过以下方式完成:

template<class Z, class...Ts>
using apply_t = Z::template apply<Ts...>;

因此,使用"本机"模板Z,您将执行Z<Ts...>。 使用这些"间接"模板,您可以apply_t<Z, Ts...>.

使用此约定,using别名的模板可以返回间接模板。 如果代码的其余部分遵循始终调用apply_t来应用模板的约定,并且您间接化您编写的所有其他模板,则我们就完成了。

这很丑陋。