c++ - 由模板参数具体化的类型的模板特化
问题描述
首先,我很抱歉问题标题,但很难描述。如果我想专门Resolve
针对 的所有实例化,下面这两个中的哪一个是有效语法A
?
1)
template<uint32_t I> struct A {};
template<typename> struct Resolve;
template<uint32_t I>
struct Resolve<A<I>>
{
void f() { printf("im here!\n"); }
};
2)
template<uint32_t I> struct A {};
template<typename> struct Resolve;
template<>
template<uint32_t I>
struct Resolve<A<I>>
{
void f() { printf("im here!\n"); }
};
或者是template<>
可选的?SO有两个不同的答案:here和here。
如有可能,请提供标准报价。
选项 2) 不在 MSVC 上编译,但至少在某些版本的 GCC 上编译。
解决方案
这是对的:
template <uint32_t I>
struct Resolve<A<I>>
{ };
该语法template <>
用于引入显式特化(类模板、函数模板等)(参见[temp.spec]/3和[temp.expl.spec]/1)。但我们正在尝试进行部分专业化。部分特化仍然需要引入模板参数,而显式特化则不需要。
另一方面,如果我们试图特化显式特化的成员,那么我们将使用template <>
. 例如:
template <class T>
struct A {
template <class T2> struct B { }; // #1
};
template <> // for A
template <class T2> // for B
struct A<int>::B<T2> { }; // #2
A<char>::B<int> x; // #1
A<int>::B<char> y; // #2
推荐阅读
- html - 嵌入式 SWF 文件大小错误
- python - 忽略 OpenCV 中 waitKey() 上的键盘事件
- ruby-on-rails - Rails 将二进制字符串转换为 .docx
- laravel - 无法验证 Laravel 中本地存储的图像
- postgresql - repmgr - 如何在故障转移后使以前的主节点成为备用节点
- javascript - 从 URL 创建对象树
- reactjs - 将鼠标悬停在 Material UI Table 中的表格行上时,如何在列单元格中显示编辑按钮?
- javascript - Undefined 不是对象——React Native
- python - 如何使用烧瓶和 HTML 显示目录中的所有图像?
- php - php - 对于不同格式的相同日期时间值,`DateTimeImmutable` 的不同行为