如何初始化重载模板的静态成员 class

How to initialize static member of a template overloaded class

我有一个 class 只有一个静态成员 list 当模板参数派生自特定基 class 时,如果参数不是派生自base class,程序不应该编译,因为静态成员不存在。

我现在遇到的问题是不知道怎么初始化list

这是代码:

#include <type_traits>

template<typename T, size_t MaxSubscribers_>
struct Event
{
    using Args_T = T;
    static constexpr size_t MaxSubscribers = MaxSubscribers_;
};

class EventManager
{
public:
    template<typename T, size_t MaxSubscribers>
    struct subscriberMap
    {
        template<typename E, typename Valid = void>
        struct events {};

        template<typename E>
        struct events<E, typename std::enable_if<std::is_base_of<Event<T, MaxSubscribers>, E>::value>::type>
        {
            static typename E::Args_T list[E::MaxSubscribers];
        };
    };
};

// my attempt, does not compile because list doesn't exsist
template<typename T, size_t MaxSubscribers>
template<typename E, typename Valid>
typename E::Args_T EventManager::subscriberMap<T, MaxSubscribers>::events<E, Valid>::list[E::MaxSubscribers];

解决方案是您必须重复定义中的确切模板参数列表。

template<typename T, size_t MaxSubscribers>
template<typename E>
typename E::Args_T EventManager::subscriberMap<T, MaxSubscribers>::events<E, typename std::enable_if<std::is_base_of<Event<T, MaxSubscribers>, E>::value>::type>::list[E::MaxSubscribers];

自 c++17 起,您可以内联声明静态成员:

static inline typename E::Args_T list[E::MaxSubscribers]{};
//     ^^^^^^                                           ^^
//                                         maybe a meaningful default value