Search code examples
c++11initializationstatic-members

How to initialize static member of a template overloaded class


I've got a class that only has a static member list when the a template argument derives from a specific base class, if the argument does not derive from the base class, the program should not compile because the static member doesn't exsist.

The problem that I now have is that I don't know how to initialize list.

This is the code:

#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];

Solution

  • The solution is that you have to repeat the exact template argument list as in the definition.

    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];