templates - 如何为封闭类的模板模板参数专门化一个嵌套类
问题描述
鉴于:
template<typename T>
struct Foo
{
template<typename U>
struct Bar {};
/* many more members */
}
和
template<typename F>
struct Zoo {};
我需要只有 Bar 将专门用于当封闭类 Foo 是Foo<Zoo<F>>
任何 F 类型时。我不想部分专门化 FooZoo<F>
因为我需要再次声明它的所有成员。
我不明白为什么以下内容无法编译:
template<typename F>
template<typename U>
struct Foo<Zoo<F>>::Bar {}
因为我希望Foo<Zoo<F>>
被视为主要的 Foo 模板,其模板参数设置为Zoo<F>
,并且只有 Bar 应该是专门的。
解决方案
一位朋友给了我解决方案,我分享。
根据 C++ 标准:
“每个类模板偏特化都是一个不同的模板,并且为模板偏特化的成员提供定义外壳”</p>
这就是代码无法编译的原因。Foo<Zoo<F>>
是 Foo 的部分特化,在这种情况下,根据 C++ 标准,编译器不使用主模板,但期望有一个不同的定义。
解决方案 1:定义封闭类的部分特化
我们必须首先定义特化, Foo<Zoo<F>>
但如果我们已经定义了它,那么我们实际上可以在这个定义中特化 Bar。
// partial specialization of Foo
template<typename T>
struct Foo<Zoo<T>>
{
template<typename U>
struct Bar { /* specialize declaration for Bar here */ };
/* many more members - should be define here as in the primary template of Foo */
};
这将给出预期的结果,但问题是我们必须在专业化中再次定义所有 Foo 其他成员。
解决方案 2:将嵌套类的声明移动到基类中
// base class contains only declaration of Bar
template<typename T>
struct FooBase
{
template<typename U>
struct Bar {};
};
// Foo contains other members, but also derived from FooBase
template<typename T>
struct Foo : public FooBase<T>
{
/* many members */
};
为了在 Foo 的类型为 时特化 Bar Foo<Zoo<T>>
,我们定义了 FooBase 的部分特化。
// partial specialization of FooBase
template<typename T>
struct FooBase<Zoo<T>>
{
template<typename U>
struct Bar { /* specialize declaration for Bar here */ };
};
推荐阅读
- reactjs - “any”类型的参数不可分配给“never”类型的参数。ts(2345)
- c++ - 解密 C++ 回溯
- jsdoc - 如何使用 jsdoc 将类型指定为类的实例?
- android - 在 Android 中将外部缓冲区导入 Vulkan 的问题
- python - 使用 python pip install git+git 设置本地 Python 环境
- linux - CircleCI 如何实现“合并”的 Docker cgroup 命名空间?
- python - 按年和月分组数据 | django 休息框架
- javascript - 如果 JavaScript 中的条件为真,我如何重复迭代?
- pandas - 删除 Pandas df 中不满足条件的重复行
- nlp - BERT权重计算