G
Grey Plastic
I have several classes that all keep track of static data. However,
the manner that they keep track of static data is identical, and so
I'm using the template<class Child> class Parent { ... }; idiom (don't
know the name of it, if there is one). The problem is that I don't
want any of my classes to have public constructors. They should be
created by a static member function.
This is what I want to do, save for the fact that this doesn't
compile:
template <class Child>
class Foo {
protected:
static Child * foo;
Foo() { }
public:
static Child * get() { if(foo==NULL) return foo=new Child(); return
foo; }
};
class Bar : public Foo<Bar> {
protected:
Bar() { }
};
class Baz : public Foo<Baz> {
protected:
Baz() { }
};
Bar * Foo<Bar>::foo = NULL;
Baz * Foo<Baz>::foo = NULL;
main() {
Bar & bar = Bar::get();
Baz & baz = Baz::get();
}
The definition of "get" is flagged as an error, because the
constructor is protected. I've tried many different things, but
nothing gives me what I want.
In my actual code, I'm keeping a static set of all the instances of
the class, but I produced this simpler snippet for the sake of
discussion.
the manner that they keep track of static data is identical, and so
I'm using the template<class Child> class Parent { ... }; idiom (don't
know the name of it, if there is one). The problem is that I don't
want any of my classes to have public constructors. They should be
created by a static member function.
This is what I want to do, save for the fact that this doesn't
compile:
template <class Child>
class Foo {
protected:
static Child * foo;
Foo() { }
public:
static Child * get() { if(foo==NULL) return foo=new Child(); return
foo; }
};
class Bar : public Foo<Bar> {
protected:
Bar() { }
};
class Baz : public Foo<Baz> {
protected:
Baz() { }
};
Bar * Foo<Bar>::foo = NULL;
Baz * Foo<Baz>::foo = NULL;
main() {
Bar & bar = Bar::get();
Baz & baz = Baz::get();
}
The definition of "get" is flagged as an error, because the
constructor is protected. I've tried many different things, but
nothing gives me what I want.
In my actual code, I'm keeping a static set of all the instances of
the class, but I produced this simpler snippet for the sake of
discussion.