Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't we define an anonymous class in place for inheritance?

Tags:

c++

standards

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.

  1. 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).

  2. 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?

like image 634
lz96 Avatar asked Dec 25 '22 14:12

lz96


2 Answers

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:

  • Start with nothing
  • Feature is needed? Add it!

Here's how a language is not developed:

  • Start with every possible feature, in an ∞-pages long standard
  • Feature not needed? Remove it!
like image 119
Lightness Races in Orbit Avatar answered Dec 27 '22 03:12

Lightness Races in Orbit


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.

like image 34
Daniel Jour Avatar answered Dec 27 '22 03:12

Daniel Jour