Can I write a test that succeeds if and only if a statement does not compile?
- by Billy ONeal
I'd like to prevent clients of my class from doing something stupid. To that end, I have used the type system, and made my class only accept specific types as input. Consider the following example (Not real code, I've left off things like virtual destructors for the sake of example):
class MyDataChunk
{
//Look Ma! Implementation!
};
class Sink;
class Source
{
virtual void Run() = 0;
Sink *next_;
void SetNext(Sink *next)
{
next_ = next;
}
};
class Sink
{
virtual void GiveMeAChunk(const MyDataChunk& data)
{
//Impl
};
};
class In
{
virtual void Run
{
//Impl
}
};
class Out
{
};
//Note how filter and sorter have the same declaration. Concrete classes
//will inherit from them. The seperate names are there to ensure only
//that some idiot doesn't go in and put in a filter where someone expects
//a sorter, etc.
class Filter : public Source, public Sink
{
//Drop objects from the chain-of-command pattern that don't match a particular
//criterion.
};
class Sorter : public Source, public Sink
{
//Sorts inputs to outputs. There are different sorters because someone might
//want to sort by filename, size, date, etc...
};
class MyClass
{
In i;
Out o;
Filter f;
Sorter s;
public:
//Functions to set i, o, f, and s
void Execute()
{
i.SetNext(f);
f.SetNext(s);
s.SetNext(o);
i.Run();
}
};
What I don't want is for somebody to come back later and go, "Hey, look! Sorter and Filter have the same signature. I can make a common one that does both!", thus breaking the semantic difference MyClass requires.
Is this a common kind of requirement, and if so, how might I implement a test for it?