我一直依赖于成员函数中定义的静态变量仅限于特定类实例的误解。成员函数中静态变量的替代
为了说明我的误解:
#include <iostream>
#include <string>
struct Simple {
template<typename T>
T & Test(const T & Value) {
static T Storage = Value;
return Storage;
}
};
int main() {
Simple A;
Simple B;
std::string Foo = A.Test(std::string("Foo"));
std::string Bar = B.Test(std::string("Bar"));
std::cout << Foo << ' ' << Bar << std::endl;
}
我所期望的行为将导致
美孚的输出杠
是否有可能导致一个简单的替代我预期的行为?
编辑
一个缩减版本,之类的有问题:
class SignalManager {
private:
template<typename T> struct FunctionPointer { typedef boost::function1<void, const T &> type; };
template<typename T> struct Array { typedef std::vector<typename FunctionPointer<T>::type> type; };
template<typename T>
typename Array<T>::type & GetArray() {
static typename Array<T>::type Array;
return Array;
}
public:
template<typename T, typename M>
void Broadcast(const M & Value) {
typename Array<T>::type::iterator Iterator;
for(Iterator = GetArray<T>().begin(); Iterator != GetArray<T>().end(); ++Iterator) {
(*Iterator)(Value);
}
}
template<typename T, typename F>
void Connect(const F & Function) {
GetArray<T>().push_back(Function);
}
};
它是完全不清楚什么这是你正在努力完成的。如果您在静态变量声明(如Mahesh所建议的)之后删除静态变量或执行指定的权限,它们都会给您预期的输出。 – greatwolf
@Victor在代码示例中,我滥用static来在编译时生成匿名成员变量。随后对'GetArray'的调用将返回一个对匿名成员变量的引用。 – Timesquare