簡體   English   中英

模板類可以在 C++ 中有 static 成員嗎

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

C++ 中的模板 class 可以有 static 成員嗎? 既然它不存在而且在使用之前是不完整的,這可能嗎?

是的。 static 成員在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

為模板的每個參數化創建一個單獨的 static 成員。 不可能在模板生成的所有類之間共享一個成員。 為此,您必須在模板外定義另一個 object。 部分特化的特征 class 可能對此有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM