0

I have a simple template class that:

  1. Is instantiated based on another class that receives callbacks.
  2. Calls an external function that takes quite a few CPU cycles.
  3. 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 ) )

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
JoshK
  • 337
  • 4
  • 16
  • 4
    What about the C++20 answer on the question you linked does not satisfy your needs? https://stackoverflow.com/a/61034367/4323 – John Zwinck Nov 15 '20 at 06:04
  • Let me clarify the question. Two things: 1. I am in a template and I don't know the name of my type 2. Is there a cleaner C++20 paradigm. (std::if_function_defined<>? ) – JoshK Nov 15 '20 at 06:08
  • 1
    @JoshK: "*you have to know the name of the type to check it. In my example, I just know that the type is "T".*" So does the answer you linked to. The `has_toString` concept is templated too. – Nicol Bolas Nov 15 '20 at 06:15
  • 1. Your type is called "T." 2. The answer I linked is a good one which is C++20 specific. – John Zwinck Nov 15 '20 at 06:20
  • I see what you are saying, I could just pass in "T". I didn't realize. But the first part of my question still stands. Is there a cleaner way to do this in c++? "std::is_invocable?" I couldn't get it to work but it seems close. – JoshK Nov 15 '20 at 06:21
  • John, thanks, those are good. I didn't think of concepts for c++20. I was hoping there was just some nice little function in the stl... – JoshK Nov 15 '20 at 06:27

0 Answers0