我想要一个可以通过其默认构造函数构造的分配器类,因为许多 STL 容器都试图创建这样的分配器。
但是,我也希望分配器共享某些公共(public)资源。
我目前的解决方案是使用一个全局变量来表示各个对象在初始化时获取的共享状态。例如,我正在做这样的事情:
const int start = 0;
template<class T>
class Counter() {
public:
Counter() : x_(start) {}
int increment() {
return x_++;
}
private:
int x_;
};
void SetStart(int s) {
start = s;
}
对于这种设置,有什么办法可以避免使用全局变量吗?我认为可以创建某种管理器类型,其子类型的构造函数访问适当的资源,但由于内部类无法访问 C++ 中外部类的成员变量,我不确定这将如何工作。
最佳答案
基本上,用 CRTP您可以跟踪基类中的计数并使用 template template
参数来保持将类模板用作派生类型的能力。
template <template <typename> class T>
class counter
{
public:
counter() { ++count; }
protected:
static int count;
};
template <template <typename> class T> int counter<T>::count(0);
template <typename T>
class X : counter<X>
{
public:
X() : x_(count) {}
private:
int x_;
};
...
X<int> x; // x_ initialized to 1
X<int> x2; // x_ initialized to 2
关于c++ - 让默认构造函数在不使用全局变量的情况下访问一些可变状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23145926/