gpt4 book ai didi

c++ - sizeof childclass 如何在父模板类中使用子类作为模板参数?

转载 作者:行者123 更新时间:2023-12-04 12:28:54 28 4
gpt4 key购买 nike

我正在逆向工程并重新创建一个实现全局静态单例的程序。 “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)];

关于c++ - sizeof childclass 如何在父模板类中使用子类作为模板参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68293403/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com