Подтвердить что ты не робот

Могут ли классы шаблонов иметь статические члены в С++

Может ли класс шаблона на С++ содержать статические элементы? Так как это не существует и является незавершенным до его использования, возможно ли это?

4b9b3361

Ответ 1

Да. Статический член объявляется или определяется внутри блока template< … > class { … }. Если он объявлен, но не определен, тогда должно быть другое объявление, которое предоставляет определение члена.

template< typename T >
class has_static {
    // inline method definition: provides the body of the function.
    static void meh() {}

    // method declaration: definition with the body must appear later
    static void fuh();

    // definition of a data member (i.e., declaration with initializer)
    // only allowed for const integral members
    static int const guh = 3;

    // declaration of data member, definition must appear later,
    // even if there is no initializer.
    static float pud;
};

// provide definitions for items not defined in class{}
// these still go in the header file

// this function is also inline, because it is a template
template< typename T >
void has_static<T>::fuh() {}

/* The only way to templatize a (non-function) object is to make it a static
   data member of a class. This declaration takes the form of a template yet
   defines a global variable, which is a bit special. */
template< typename T >
float has_static<T>::pud = 1.5f; // initializer is optional

Для каждой параметризации шаблона создается отдельный статический член. Невозможно, чтобы один член был общим для всех классов, сгенерированных шаблоном. Для этого вы должны определить другой объект вне шаблона. С этим может помочь класс частично специализированных признаков.