首页 > 解决方案 > 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> {
      ^

标签: c++templates

解决方案


你可以这样做,但它不太理想:

template <class TClass>
class B
{
    static char cBuffer[];
};

class A : public B<A> {
  int a;
  int b;
};

template <>
char B<A>::cBuffer[sizeof(A)];

推荐阅读