3

I have a base class:

template <typename T>
class Base
{
    public:
        struct RegisterType {
            RegisterType() { RegisterHelper::get().registerType<T>();}
        };

        static RegisterType s_register;
};

template <typename T>
typename Base<T>::RegisterType Base<T>::s_register __attribute__((used));

and a derived class:

class Derived : public Base<Derived>
{
    public:
        constexpr static const char *const propertyA = "propertyA";
        ...
}

Derived types need to be registered in order to map some properties to derived type id and, therefore, make a cleaner data driven loader. However, I don't want to explicitly register them in an outer class, so my target is that Derived type registration is inside Derived type definition.

The problem I found is that there are some Derived classes that are not used in the project code and, in consequence, those derived classes are not registered, which lead to incomplete final result in loader. This is fixed if I explicitly include the Derived type in question(i. e. DerivedOne), such as: '#include "DerivedOne.h"'

Is there any way to force its initialization without having to explicitly include all derived classes?

Thanks in advance

omniyo
  • 330
  • 2
  • 6
  • 19
  • 1
    Is there a `DerivedOne.cpp`? – Max Langhof Jan 22 '19 at 12:49
  • 5
    when the code is not included anywhere it wont get compiled at all, or do I miss something? – 463035818_is_not_an_ai Jan 22 '19 at 12:49
  • Registering everything explicitly seems to be a good idea. Also see related question [Force construction of a global object](https://stackoverflow.com/questions/54055604/force-construction-of-a-global-object/54055775#54055775) – user7860670 Jan 22 '19 at 12:53
  • 1
    @MaxLanghof we can have it if required. I already tried creating a DerivedOne.cpp, with no luck – omniyo Jan 22 '19 at 12:53
  • C++17 `inline`? https://stackoverflow.com/questions/38043442/how-do-inline-variables-work – Marek R Jan 22 '19 at 13:03
  • 2
    @omniyo Well, if your code (of any kind) is exclusively in a `.h` and no compilation unit includes that `.h` then the code might as well not exist. – Max Langhof Jan 22 '19 at 13:04
  • Make a script that produces a source file that include all header file of your project and compile it! – Oliv Jan 22 '19 at 13:33
  • @Oliv that's a good idea that I already thought but if I have to include derived classes headers from another project, I have to add the dependency into the original project – omniyo Jan 22 '19 at 13:57
  • @MaxLanghof even spreading the code into .h and .cpp files, the static member is not initialized. So it is not exclusively in a .h – omniyo Jan 22 '19 at 14:00

0 Answers0