1

Assume there is a class Foo that I, as the designer of a library, do not want my users to be able to instantiate more than n amount of times (where n is not necessarily 1). Is there any way to enforce this rule during compilation?

Please note that I am not after a Singleton or likewise pattern, as I would like the users to realize they should not instantiate the class, before executing their code.

So far, my best attempt was a combination of static_assert and the __COUNTER__ macro but to no avail as they do not seem to be evaluated, as I'd expect, inside functions or classes.

constexpr int bar()
{
    static_assert( __COUNTER__ < 5, "You called this too many times!");
    return 0;
}
Davis Herring
  • 36,443
  • 4
  • 48
  • 76
platisd
  • 153
  • 1
  • 9
  • 4
    This kind of check cannot be done at compile time, only at runtime. If you don't want to use a singleton, make the counter be a static member of the class, increment the counter in the constructor, and have the constructor throw an exception once the counter has been exceeded. – Remy Lebeau Oct 13 '18 at 15:02
  • 1
    Yeah, I am afraid it is as you say... It is a little disappointing because looking at `static_assert` and `__COUNTER__` seemed like the building blocks for such a solution could be there. – platisd Oct 13 '18 at 15:17

1 Answers1

2

No. Even leaving aside the fact that a single function making a single instance could be called multiple times, or that instantiation could occur in a loop or template, nothing could stop instantiation from occurring in another translation unit.

Davis Herring
  • 36,443
  • 4
  • 48
  • 76