Uses of pointers non-type template parameters?

后端 未结 5 1030
小蘑菇
小蘑菇 2020-12-13 11:03

Has anyone ever used pointers/references/pointer-to-member (non-type) template parameters?
I\'m not aware of any (sane/real-world) scenario in which that C++ feature sho

5条回答
  •  长情又很酷
    2020-12-13 11:08

    The case for a pointer to member is substantially different from pointers to data or references.

    Pointer to members as template parameters can be useful if you want to specify a member function to call (or a data member to access) but you don't want to put the objects in a specific hierarchy (otherwise a virtual method is normally enough).

    For example:

    #include 
    
    struct Button
    {
        virtual ~Button() {}
        virtual void click() = 0;
    };
    
    template
    struct GuiButton : Button
    {
        Receiver *receiver;
        GuiButton(Receiver *receiver) : receiver(receiver) { }
        void click() { (receiver->*action)(); }
    };
    
    // Note that Foo knows nothing about the gui library    
    struct Foo
    {
        void Action1() { puts("Action 1\n"); }
    };
    
    int main()
    {
        Foo foo;
        Button *btn = new GuiButton(&foo);
        btn->click();
        return 0;
    }
    

    Pointers or references to global objects can be useful if you don't want to pay an extra runtime price for the access because the template instantiation will access the specified object using a constant (load-time resolved) address and not an indirect access like it would happen using a regular pointer or reference. The price to pay is however a new template instantiation for each object and indeed it's hard to think to a real world case in which this could be useful.

提交回复
热议问题