C++ Library & Self registering classes: Factory map empty in client application

前端 未结 1 1057
傲寒
傲寒 2021-01-07 10:23

Let there be a C++ library (let\'s call it lib) which gets included as a static library in an application (let\'s call it app). Within the li

1条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-07 10:52

    From the blog post, you are missing the static member registered (also called "// The really fun part"). Having and instantiating such a static variable in the base class forces it to be instantiated in all derived classes and this will register the class as a side effect.

    EDIT: There is another very small but very important piece of code in the blog post:

        Registrar() : Base(Key{}) { (void)registered; }
    

    This will ensure that registered is used. Because a static variable is only instantiated the first time it is used, otherwise the function is not called.

    In your case, adding the following to node_template should work:

    template 
    struct node_template :
        node,
        factory::registrar
    {
        node_template(const std::string& uuid_string) :
            node(uuid_string),
            factory::registrar(uuid_string)
        {
            (void) registered;
        }
    
        static bool do_register() {
            derived d; // I am not sure if one should in some way force this to not be optimized away.
            return true;
        }
    
        inline static bool registered = do_register();
    };
    

    0 讨论(0)
提交回复
热议问题