Ensure at compile time that a method is called in exactly one place

Low Tech Approach:

Since you have control over the code structure (which includes the build system, I assume), here is a low tech solution:

  • make the function name sufficiently unique
  • grep for the function name in your code. You are expecting it twice (assuming that you declaration and definition are colocated):
    • Once in the header
    • Once at the single call site

Alternatively:

If you really, really, really want to solve it with C++, then you could try

  • Use a compile time counter to figure out the number of uses within a compilation units
  • Make sure that the function would violate ODR if the header is included in multiple compilation units.

However, compile time counters are black magic (says I, and I really like TMP), and forcing ODR violations for this purpose seems like similar voodoo (at least you would require a test case that fails to link).

But seriously:

Don't do this. Whatever you do, it can be perverted with almost no effort by a wrapper function:

auto call_my_method(MyClass& o)
{
   return o.my_method();
}

MyClass::my_method() is called only in the wrapper. Everybody else just calls the wrapper which is probably even inlined by the compiler.

As others suggested: It might be much more helpful if you would explain what you are trying to do.


Here's a rough idea that may work (too long for a comment - but incomplete for a good SO answer).

You may be able to achieve this by counting/checking template instantiations.
Templates are instantiated only upon use.

Similarly, template method/function bodies are not parsed nor compiled or linked (beyond ensuring valid syntax) if they are never called. This means that any instantiations within their bodies are not made).

You may be able to create a template that maintains some global instantiation count and static assert on that (or some other TMP mechanism to check past instantiations).

Tags:

C++