c++ - 用另一个类模板实例化一个类模板会导致使用不完整的类型
问题描述
假设我们有以下类模板:
template<size_t S>
struct A
{
char str[S];
};
template<typename T>
class B
{
T t;
public:
void init(); // Should initialize the 't' member in some a way.
};
现在,如果我专门init
用一些非模板类型作为模板的参数B
,就可以了。但是,如果不指定它的值,我不能将它A
作为参数专门化。即,我想做这样的事情:B
S
template<>
void B<A<S>>::init()
{
// Initialize the 't.str'. For example:
memset(t.str, 0, S);
}
解决方案
要提供执行特定于 的部分特B<A<???>>
化,您实际上需要为类提供这样的部分特化:
#include <cstddef>
#include <cstring>
#include <iostream>
template<std::size_t S>
struct A
{
char str[S];
};
template<typename T>
class B
{
T t;
public:
void init(); // Should initialize the 't' member in some a way.
};
template<std::size_t S>
class B<A<S>> {
using T = A<S>;
T t;
public:
void init(); // Should initialize the 't' member in some a way.
};
template<std::size_t S>
void B<A<S>>::init()
{
// Initialize the 't.str'. For example:
std::memset(t.str, 0, S);
std::cout << "Initialized B<A<" << S << ">>\n";
}
int main() {
B<A<3>> b;
b.init();
}
请注意,您的代码有两个主要区别:
- 类模板有部分特化
template<std::size_t S> class B<A<S>>
- 该类模板的
init
成员函数现在可以定义为template<std::size_t> void B<A<S>>::init() { /* ... */ }
如果在您的用例中没有其他实例有效,您可以省略类模板的基本案例定义B
并将其替换为。template<typename T> class B;
推荐阅读
- python - 使用 Python 扩展时在 VS Code 中查看 Ipython Notebooks 的基于行的差异
- django - Django migration duplicate operation
- neural-network - 有人可以解释一下我们如何用重量减去梯度
- python - python中的'del'函数可以同时从两个列表中删除元素吗?
- javascript - 从横向切换到纵向视图时阅读更多阅读更少功能不起作用
- sensors - 将数据从 MAX30100 发送到 ESP8266 到 Thingspeak
- javascript - JavaScript Canvas 中的 HSB 颜色填充
- amazon-kinesis - Kinesis 无效的流标头
- java - 在java中计算一个数组行和一个索引的最大值
- javascript - 如何为受密码保护的链接提供元数据?