模板类可以在C++中具有静态成员

rub*_*buc 29 c++ templates static-members

C++中的模板类可以有静态成员吗​​?由于它不存在并且在使用之前是不完整的,这可能吗?

Pot*_*ter 36

是.静态成员在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
Run Code Online (Sandbox Code Playgroud)

为模板的每个参数化创建单独的静态成员.在模板生成的所有类中共享单个成员是不可能的.为此,您必须在模板外定义另一个对象.部分专业的特质类可能对此有所帮助.

  • 对于稍后访问该线程的任何人,可以通过编写“has_static&lt;int&gt;::fuh()”(或用任何其他类型代替“int”来实例化函数“fuh”,因为此类并不真正使用`int`)。 (2认同)