Compile-time assertions are a way to check conditions during compile time instead of runtime. It’s always good to make sure types, sizes, and template parameters are as you expect them to be.
In this example, this assertion is checking that child classes extend the right base class. If you try to compile this code (C++11 support needed), you will get the error about missing inheritance (pun intended).
#include <type_traits>
#include <string>
using namespace std;
class ParserPolicyBase
{
};
class XMLParserPolicy : public ParserPolicyBase
{
public:
void doParse(const std::string &input)
{
}
};
class JSONParserPolicy
{
public:
void doParse(const std::string &input)
{
}
};
int main()
{
static_assert(std::is_base_of<ParserPolicyBase, XMLParserPolicy>::value, "ParserManager should inherit from XMLParserPolicy");
static_assert(std::is_base_of<ParserPolicyBase, JSONParserPolicy>::value, "ParserManager should inherit from JSONParserPolicy");
return 0;
}
2.1-compile-assert.cc: In function ‘int main()’:
2.1-compile-assert.cc:28:72: error: static assertion failed: ParserManager should inherit from JSONParserPolicy
28 | static_assert(std::is_base_of<ParserPolicyBase, JSONParserPolicy>::value, "ParserManager should inherit from JSONParserPolicy");