衆所周知,例程,函數或方法(「成員函數」)的變量static
。創建每個實例化和每個包含實例的方法變量靜態效果
(快速回顧和完整性檢查)
在通常情況下,這正是一個變量:
int f() {
static int i = 0;
return i++;
}
也就是說,有一個變量i
是created in .BSS/.DATA那「屬於」功能f
。對於模板,它的每個唯一實例之一:
template <typename T> int f() {
static int i = 0;
return i++;
}
int g() {
return f<int>() + f<int>() + f<int>() + f<float>();
}
在這裏,有兩個獨特的實例(f<int>
和f<float>
),所以有兩個i
S IN的.BSS/.DATA段。
問題
我想一些方法,使模板成員函數的變量都住每實例和每個實例其封閉類的。我有興趣實現這種效果,或多或少需要任何性能手段(可能根本不涉及靜態)。我應該怎麼做?
例如:
class Foo { public:
template <typename T> int f() {
static int i = 0;
return i++;
}
};
void g() {
Foo foo1;
Foo foo2;
/*
These will have values a=0, b=0, c=1. This happens because there are two
variables:
"Foo::f<float>()::i"
"Foo::f<double>()::i"
What I *want* is for there to be three variables:
"Foo::f<float>()::i" (foo1's copy)
"Foo::f<float>()::i" (foo2's copy)
"Foo::f<double>()::i" (foo1's copy)
So the result is a=0, b=0, c=0. How can I accomplish this effect (maybe
not using static)?
*/
int a = foo1.f<float>();
int b = foo1.f<double>();
int c = foo2.f<float>();
}
能夠在任何downvoters的請給一個原因?似乎是一個寫得很好的問題,雖然可能是一個XY問題... – ildjarn
Idk爲什麼這裏有兩個密切的選票。這個問題非常清楚(儘管肯定很難回答)。 –