【发布时间】:2017-02-20 17:31:52
【问题描述】:
众所周知,static 例程、函数或方法的变量(“成员函数”)exist for each unique instantiation。
(快速审查和健全性检查。)
通常情况下,这只是一个变量:
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>),因此 .BSS/.DATA 段中有两个 is。
问题
我想要一些方法让模板成员函数中的变量同时存在于它们的封闭类的 per-instance 和 per-instantiation 中。我有兴趣通过或多或少的任何必要的性能手段(可能根本不涉及静态)来实现这种效果。我该怎么做?
例如:
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>();
}
【问题讨论】:
-
能否请任何反对者给出理由?对我来说似乎是一个写得很好的问题,尽管可能是一个 XY 问题......
-
我知道为什么这里有两个接近投票。这个问题很清楚(虽然肯定很难回答)。