johnbakers johnbakers -4 years ago 43
C++ Question

What is easiest way to force compiler to throw error?

To the folks marking this as duplicate: it is not; the other question addresses

enum
s which are compile-time constants. This is not a constant integral expression thus the solution would be very different. Please see my code below more carefully before suggesting this has already been answered in another question, as it has not in any way. I am checking the value of a member variable on an object, information created at runtime, and I'm curious what I can do with that in this context.




I'm at a point where I need to use something to make the compiler fail if the user of my API does something she should not.

I don't know if that's possible, it is? The options I mention above are primarily run-time, right?

For example, suppose you have a function:

void doSomethingIncredible(AwesomeClass amazingObject)
{
//perform life-changing work here except:
if (amazingObject.isntAmazing) //a bool property of object
//uh oh, life sucks, I refuse to compile this


Now calling this function will change how you live your life in all respects, except for occasions in which
amazingObject
has a particular property switched on, for example, in which case, I want the compiler to not even allow this to pass, i.e. cannot run the program.

Somewhere in the body of the function is a c++ mechanism that forces compiling to fail, which alerts the user that you cannot use this function for such an inferior un-amazing object.

Is this possible?

To clarify, this is something I want to do a compile time based the contents of a variable, as shown in my example above. The suggestion to use
static_assert
does not apply here.

Answer Source

The only way I can see to get it compile time checked is to subclass AwesomeClass and restrict the new class' creation to only be able to create objects where amazingObject.isntAmazing is never true. Then change the signature to;

void doSomethingIncredible(AwesomeAndAmazingClass amazingObject)

That will prevent the call to the method for objects that are simply awesome but not amazing.

As a maybe more illustrative example (not compiled, so consider pseudo code);

class Thing {
  protected: 
    Color _color;
    Shape _shape;
  public:
    Thing(Color color, Shape shape) {
      _color=color; _shape=shape;
    }
}

class GreenThing : Thing {
  public:
    GreenThing(Shape shape) : Thing(Color.Green, shape) {}
}

void doSomethingIncredible(GreenThing specialThing)
{
  // specialThing here is still a Thing, but also compile time
  // checked to also always be a GreenThing
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download