简体   繁体   English

模板类可以在 C++ 中有 static 成员吗

[英]Can template classes have static members in C++

Can a template class in C++ have static members? C++ 中的模板 class 可以有 static 成员吗? Since it doesn't exist and is imcomplete before it is used, is this possible?既然它不存在而且在使用之前是不完整的,这可能吗?

Yes.是的。 The static member is declared or defined inside the template< … > class { … } block. static 成员在template< … > class { … }块中声明或定义。 If it is declared but not defined, then there must be another declaration which provides the definition of the member.如果已声明但未定义,则必须有另一个声明提供成员的定义。

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

A separate static member is created for each parameterization of the template.为模板的每个参数化创建一个单独的 static 成员。 It is not possible to have a single member shared across all classes generated by the template.不可能在模板生成的所有类之间共享一个成员。 For that, you must define another object outside the template.为此,您必须在模板外定义另一个 object。 A partially-specialized traits class might help with that.部分特化的特征 class 可能对此有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM