Es ist bekannt, dass static
Variablen einer Routine, Funktion oder Methode ("Member-Funktion") exist for each unique instantiation.Erstellen von Wirkung der Methode Variable statische pro Instanz und pro umschließende Instanz
(. Quick Review und Plausibilitätsprüfung)
Im gemeinsamen Fall ist dies genau eine Variable:
int f() {
static int i = 0;
return i++;
}
Das heißt, es gibt eine einzelne Variable i
die created in .BSS/.DATA ist, dass "gehört" zur Funktion f
. Bei Vorlagen, dann ist es ein pro einmaliger Instantiierung:
template <typename T> int f() {
static int i = 0;
return i++;
}
int g() {
return f<int>() + f<int>() + f<int>() + f<float>();
}
Hier gibt es zwei einzigartige instantiations (f<int>
und f<float>
), und so gibt es zwei i
s im .bss/.DATA Segment.
Problem
Ich möchte eine Möglichkeit Variablen in Vorlagen-Element-Funktionen zu machen, leben beide pro Instanz und pro-Instanziierung ihrer umgebenden Klasse. Ich bin daran interessiert, diesen Effekt zu erreichen, indem mehr oder weniger leistungsfähige Mittel notwendig sind (möglicherweise überhaupt keine statischen). Wie soll ich das machen?
Zum Beispiel:
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>();
}
Kann eine des downvoters bitte geben ein Grund? Scheint wie eine gut geschriebene Frage zu mir, obwohl möglicherweise ein XY-Problem ... – ildjarn
Idk, warum es zwei nahe Stimmen hier gibt. Die Frage ist ziemlich klar (aber definitiv schwer zu beantworten). –