class MyClass : SomeFeatureGeneratedByTemplate<MyClass>
Template offers much convenience to add a feature to our class just by inheriting a instantiated class template.
However, sometimes the feature may get too complicated to be implemented by template, where macro might be the only choice.
MACRO_TO_GENERATE_COMPLICATED_FEATURE(MyClass)
/* Might be expanded to
#ifndef MYCLASS_FEATURE_CLASS
#define MYCLASS_FEATURE_CLASS
class MyClassFeature { ... };
#endif
*/
class MyClass : MyClassFeature
I wonder if the following syntax would simplify this: allow to define a anonymous class just in place
class MyClass : class { ... }, class{ ... }
Therefore, the above code could be rewritten as:
class MyClass : MACRO_GEN_FEATURE(MyClass)
APPEND:
Q: Why don't I embed the code just inside class?
A:
1. This feature should be explicit and exposed to user. When they generating docs, derived class is easy to discover :class A: FEATURE1(A), FEATURE2(A)
while embedded macro isn't. Although an empty class could be derived to achieve our goal(e.g class A: FEATURE1(A)//just derive predefined struct FEATURE1_EMPTY{};
), apparently it is not a perfect solution.
Sometimes we even needn't to get any member from the class generated by macro, but that class has to include member to provide some function(e.g static_assert
with some helper class templates).
Complete specialization of a nested class template is not allowed, which prevents me from using nested class to avoid namespace conflicts mentioned in 2).
I know that this is illegal right now, but why is this not allowed in C++ standard?
Because neither Bjarne (in the 1980s) nor anybody on the ISO committee (1990s—now) saw a need for this. I've never seen a need for it until this macro hackery today.
Here's how a language is developed:
Here's how a language is not developed:
class MyClass : class { /* CONTENT */ } {
// HERE
};
What ever you would put where CONTENT
is, would be only used or even accessible from the class MyClass
, so it can equally well be written where the HERE
stands.
If you want to "organise" the contents of a single class, you could use "nested" classes to enhance encapsulation:
class Thing {
class SomeSubThing {} subthing;
};
Though whether this useful or even recommendable is highly depended of the actual case and probably highly subjective.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With