mercredi 24 mars 2021

Expose only class instances in C++

I'm trying to define a class where explicit instantiation is prohibited. The user must be able to use only a limited set of instances.

In term of code I'm currently doing something like this:

class Obj
{
private:
  int _x;
  Obj(int x) : _x() {}

public:
  static const Obj obj1;
  static const Obj obj2;
};

const Obj Obj::obj1(1);
const Obj Obj::obj2(2);

int main()
{
  Obj o1 = Obj::obj1;
}

The constructor is private and class instances are available thru Obj::xxx.

With this approach however, I don't like the fact an instance is visible from another one.

(i.e. I don't want Obj::obj1.obj2.obj1 to be a valid syntax)

Is there any workaround or better patterns to avoid such behaviour?

Aucun commentaire:

Enregistrer un commentaire