mercredi 8 avril 2020

Create constrexpr function with macro behaviour

I have a macro function which works as you would expect:

#define PRECONDITION(testBool) ( !(testBool) ?              \
    ( fprintf(stderr, "%s:%i: Precondition '%s' failed.\n", \
              __FILE__, __LINE__, #testBool),               \
      exit(1) ) : void(sizeof(0)) )

This is great, since I can create nice assertions:

PRECONDITION(5 > 6); // prints "<file>:<line>: Precondition '5 > 6' failed."

While this works, I'm trying to learn a better and more modern way of doing this, using constexpr, so I can have type safety, use std::err <<. However, I have not been able to find a source stating how to do this / whether or not it is actually possible, so I ask here. What I image is something along the lines of:

constexpr void PRECONDITION(bool testBool)
{
    if(testBool) { return; }
    std::cerr << __SOME_MAGIC__ << ":" << __SOME_MAGIC__ << ":"
        << "Precondition '" << __SOME_MAGIC__ << "' failed." << std::endl;
}

Is it possible to achieve this behaviour?

Aucun commentaire:

Enregistrer un commentaire