c++ - sizeof 子类如何在父模板类中使用,子类作为模板参数?
问题描述
我正在逆向工程并重新创建一个实现全局静态单例的程序。“A”是存储在单例中的类,“B”是单例本身。有什么办法可以使下面的代码工作?
template <class TClass>
class B
{
static char cBuffer[sizeof(TClass)];
};
class A : public B<A> {
int a;
int b;
};
此代码段生成以下错误:
<source>:4:22: error: invalid application of 'sizeof' to an incomplete type 'A'
static char cBuffer[sizeof(TClass)];
^~~~~~~~~~~~~~
<source>:7:18: note: in instantiation of template class 'B<A>' requested here
class A : public B<A> {
^
<source>:7:7: note: definition of 'A' is not complete until the closing '}'
class A : public B<A> {
^
解决方案
你可以这样做,但它不太理想:
template <class TClass>
class B
{
static char cBuffer[];
};
class A : public B<A> {
int a;
int b;
};
template <>
char B<A>::cBuffer[sizeof(A)];
推荐阅读
- rest - 使用 API 在 BigQuery 中创建数据集
- debian - 如何使用 Qubes OS 从 Debian 9 升级到 Debian 10?
- haskell - 在 Haskell 中连接两个通用的 Either
- python - 将带有 url 的字符串格式的 DataFrame 正确转换为 JSON
- c++ - 如果我已经创建了初始化结构数组的构造函数,通过什么调用该方法?
- java - 如何解决我的安卓登录问题?
- c# - 这是传递给带有 in 关键字的方法的只读结构的防御性副本吗
- scala - Intellij idea scala worksheet 内部错误:java.lang.NoClassDefFoundError: scala/Serializable
- javascript - 将对象转换为数组并按对象键对它们进行分组
- swift - 以编程方式快速更新图像高度