如何在不声明类型的情况下将模板发送到另一个模板

How to send a template to another template without declaring the type?

本文关键字:另一个 情况下 声明 类型      更新时间:2023-10-16

我正在尝试编译以下代码:

#include <iostream>
template<class T> struct Container1;//forward declaration
template<class T> struct Container2;//forward declaration
template<class Container,class Type>
using _Make_Container=typename Container<Type>;
template<class T>
struct Container1
{};
template<class T>
struct Container2
{};
int main()
{
    _Make_Container<Container1,int> a;
}

给了我一些错误:

 expected nested-name-specifier before 'Container'
  using _Make_Container=typename Container<Type>;
                                ^
 error: 'Container' is not a template

对我来说似乎没问题,因为我们将Container1int发送到using,然后它变成:

using _Make_Container=typename Container1<int>;
//then 
Container1<int> a;

我不明白那个错误的原因!!任何想法?

这些错误信息非常清楚。


 using _Make_Container=typename Container<Type>;
                          ^

您没有引用嵌套依赖类型,因此这里不需要typename关键字。阅读这篇文章,了解typename在哪些地方是必需的。

错误:'Container'不是模板

就像它说的,你的别名模板不表明Container是一个模板,但它继续使用它作为一个模板。您需要为Container

使用模板模板参数
template<template<typename> class Container,class Type>
using _Make_Container = Container<Type>;

借鉴Yakk的优秀建议,您应该将别名模板定义更改为

template<template <typename...> class T1, typename... T2>
using Make_Container = T1<T2...>;

这允许您执行以下操作:

template<class T, class T1>
struct Container2
{};
Make_Container<Container2,int,long> b;

最后,使用前导下划线后跟大写字母的名称由实现保留。所以你应该把_Make_Container重命名为Make_Container

您必须像这样编写别名模板

template<template <typename> class T1,class T2>
using _Make_Container= T1<T2>;
template< template <class> class Container,class Type>
using _Make_Container = Container<Type>;
相关文章: