在声明前使用静态常量成员

Using static const member before declaration

我的问题如下:

template<typename T> 
struct A {
    T* array[B<T>::N];
};

template<typename T>
struct B {
    static const int N = 10;
    A<T> a;
}

这不会编译,因为我需要某种前向声明。我看到两个选项

有没有办法编译此代码(如果可能,无需更改任何类型或引入更多模板参数)?

有很多类似的问题,但对大多数人来说,答案是这样的:"No you cant forward (static) class members" 以下是其中一些:

forward declare static function c++

Is it possible to forward declare a static array

c++ forward declaration of a static class member

您可以稍微更改 类 来解决这个问题。

解决方案 1:使 N 成为 A

的成员
template<typename T> 
struct A {
    static const int N = 10;
    T* array[N];
};

并根据 A<T>::N.

定义 B<T>::N
template<typename T>
struct B {
    static const int N = A<T>::N;
    A<T> a;
};

解决方案 2:使 N 成为 A

的另一个模板参数
template<typename T, int N> 
struct A {
    T* array[N];
};

template<typename T>
struct B {
    static const int N = 10;
    A<T, N> a;
};