In the project I'm working on we have a large number of classes with methods named to match enum keys. This provides a means to call functions that can be dynamically detected.
General example of these classes:
template <class ImplType>
class BaseTemplate
{
...
};
class A : public BaseTemplate<A>
{
public:
enum class Methods : int
{
DoAThing,
SecondItem,
ItemNumberThree,
FinalAction
};
private:
void doAThing();
void secondItem();
void itemNumberThree();
void finalAction();
};
The methods are called by another mechanism (more on this below). I'd like a means to have a compile-time check that the method names match the keys in the enum, so to have a compiler error if a key in the enum is not matched by a function.
Notes:
- The classes inherit a base class with other business functionality (not shown). Since this is using CRTP to capture the type of the derived object, we would ideally add checks there.
- I can use C++20 and potentially C++23, so
constevaland similar features are available. - As in the example, enum keys must be CapitalCamelCase, methods named lowerCamelCase. The only difference is the case of the first letter.
- This is a Qt project -- the enum here is a
Q_ENUMand the methods areprivate Q_SLOT. I've not put these in the example, as if possible I'd prefer a pure C++ solution.
In the actual application, we use meta-object reflection to enumerate the enum keys, and so to achieve calls to the possible methods. However, I suspect the Qt metaobject system is unlikely to be useful for compile-time checks. We already have run-time assertions on missing methods. If Qt can somehow be used for this, perhaps after the Moc compile step, that would be acceptable.
enumvalues as NTTP to a generic function that handles everything. Ideally, the template shouldn't be a none-static member(thiswould be the 1st argument). And for template functions, I'd rather use a lambda or CPO - such thatstd::bindand other functional manipulations be easier.