問題描述
通常一個類的靜態成員/對象對于具有靜態成員/對象的類的每個實例都是相同的.無論如何,如果靜態對象是模板類的一部分并且還依賴于模板參數呢?例如,像這樣:
Usually static members/objects of one class are the same for each instance of the class having the static member/object. Anyways what about if the static object is part of a template class and also depends on the template argument? For example, like this:
template<class T>
class A{
public:
static myObject<T> obj;
}
如果我將 A 的一個對象轉換為 int
并將另一個對象轉換為 float
,我想會有兩個 obj
,一個用于每種類型?
If I would cast one object of A as int
and another one as float
, I guess there would be two obj
, one for each type?
如果我創建多個類型為 int
和多個 float
的 A 對象,它是否仍然是兩個 obj
實例,因為我我只使用兩種不同的類型?
If I would create multiple objects of A as type int
and multiple float
s, would it still be two obj
instances, since I am only using two different types?
推薦答案
靜態成員對于每個不同的模板初始化都是不同的.這是因為每個模板初始化都是由編譯器在第一次遇到模板的特定初始化時生成的不同類.
Static members are different for each diffrent template initialization. This is because each template initialization is a different class that is generated by the compiler the first time it encounters that specific initialization of the template.
靜態成員變量不同的事實由這段代碼顯示:
The fact that static member variables are different is shown by this code:
#include <iostream>
template <class T> class Foo {
public:
static int bar;
};
template <class T>
int Foo<T>::bar;
int main(int argc, char* argv[]) {
Foo<int>::bar = 1;
Foo<char>::bar = 2;
std::cout << Foo<int>::bar << "," << Foo<char>::bar;
}
結果
1,2
這篇關于C++ 靜態模板成員,每個模板類型一個實例?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!