I have a simple template class that:
- Is instantiated based on another class that receives callbacks.
- Calls an external function that takes quite a few CPU cycles.
- Calls into the class that receives the callbacks.
In code:
template <class T>
class Caller {
public:
T & destination_;
Caller( T & destination ) : destination_{ destination } {}
void DoSomethingExpensive() {
if ( ExpensiveExternalFunction() )
destination_.ExternalFunctionDone();
}
};
If the ExternalFunctionDone()
in the destination class doesn't do anything then we will have wasted a lot of compute time in ExpensiveExternalFunction()
. Because this is an external function, the compiler can't just optimize all of this away.
Would there be a way in C++20, perhaps using some SFINAE magic, that we could allow the class T
to simply not implement ExternalFunctionDone()
?
This seems close (Templated check for the existence of a class member function?), but you have to know the name of the type to check it. In my example, I just know that the type is "T".
Also, I am hoping that there's something nice and clean in C++20 that wraps all of this up in something like:
if constextpr( std::method_exists( T::ExternalFunctionDone ) )