vladon
vladon

Reputation: 8401

How to compile-time detect functions that overloaded important template?

Suppose we have a template:

template <class T>
void VeryImportantFunction(T t) {
    // something
}

Somewhere it is called with something like:

// ..
int a = 12345;
VeryImportantFunction(a);
// ..

It is very big project with tons of source code, and occasionally somewhere in deep of the code appears a new header with overloaded function:

void VeryImportantFunction(int t) {
    // totally another behavior
}

And code fragment above will call overloaded function, because it have more priority.

Can we somehow disable or in another way compile-time detect functions that can overload our important template?

Upvotes: 1

Views: 78

Answers (2)

Bathsheba
Bathsheba

Reputation: 234665

Write

inline void VeryImportantFunction(int t)
{ 
    VeryImportantFunction<int>(t); // call the template function
}

immediately after your template definition.

Then if someone has written their own version of void VeryImportantFunction(int t), you'll get a compiler error.

Upvotes: 1

Vittorio Romeo
Vittorio Romeo

Reputation: 93264

Your question is unclear, but here's my take on it.


If you want to hit the template overload, you can simply invoke the function by explicitly specifying the template parameters:

int a = 12345;
VeryImportantFunction<int>(a);

If you want this from happening again in the future, then make VeryImportantFunction either a lambda or a struct - those cannot be overloaded "externally":

inline const auto VeryImportantFunction = [](auto x){ /* ... */ };
// no one can overload this!

If you want to know all the overloads of VeryImportantFunction without external tooling, then call it in a completely wrong way - the compiler error will likely show all considered overloads:

VeryImportantFunction(5, 5, 5, 5); 
// error... will likely show all candidates

Upvotes: 8

Related Questions