c++ - 具有类型和模板模板参数的模板类中类型参数的部分特化

标签 c++ templates partial-specialization template-templates

我想专门化以下模板类的类型参数,它有一个类型参数和一个模板模板参数:

template <
    typename T,
    template <typename E> class Foo
> class Bar;

我尝试了添加和/或省略 .template 的所有排列组合和 typename在以下每个片段的最后一行,都没有编译:

1.)

template <
    template <typename E> class Foo
> class Bar<int, Foo<typename E>>;

2.)

template <
    template <typename E> class Foo
> class Bar<int, Foo.template <typename E>>;

3.)

template <
    template <typename E> class Foo
> class Bar<int, Foo<E>>;

4.)

template <
    template <typename E> class Foo
class Bar<int, Foo.template <E>>;

为什么它们都不起作用?

关于每个适用片段的最后一行:

  • 不是typename澄清E是类 Foo 使用的类型, 或者此语法只能在 {} 中使用Bar的正文的类定义?
  • 不是template澄清Foo是一个模板,因此阻止编译器解析 Foo <作为Foo “小于”,或者此语法只能在 {} 中使用Bar的正文的类定义?

我怎样才能让它工作?

最佳答案

Doesn't typename clarify E is a type used by class Foo, or can this syntax only be used within the {} body of Bar's class definition?

typename 仅在您在模板定义中定义类型时使用(class 也可以使用)或当您访问依赖类型(一种类型取决于模板参数)。

有关更多信息(甚至关于何时使用 template),请参阅 this thread .

How can I get this to work?

模板模板参数中类型的名称实际上不能使用。这只是一种形式。您必须向主模板添加另一个模板参数:

template <
    template<typename> class Foo,
    typename E
> class Bar<int, Foo<E>> { ... };

此外,如果这是模板 Bar 的特化,则 Bar 需要一个主模板来特化:

template<typename T, typename U>
struct Bar;

template <
    template<typename> class Foo,
    typename E
> class Bar<int, Foo<E>> { ... };

关于c++ - 具有类型和模板模板参数的模板类中类型参数的部分特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23860571/

相关文章:

c++ - 指针 - 删除

c++ - 浮点常量值不同,具体取决于它的声明方式 C++ (Xcode IDE)

c++ - 嵌套在类模板中的类的前向声明是否合法?

C++ 部分模板特化 - 设计简化

c++,对每个数组成员执行函数

c++ - Tab '\t' 间距不一致

function - 在 if 语句中使用函数 return 或在 go 模板中使用变量

c++ - 调用模板 bool 函数的最佳方式

c++ - 这个条件如何放在模板偏特化中?

c++ - 我应该怎么做而不是函数模板的部分特化?