Passing a pointer to a member function as a template argument. Why does this work?

前端 未结 2 1605
有刺的猬
有刺的猬 2021-02-12 11:40

I have some code that 100% works for the use case I have. I\'m just wondering if anyone can explain how and why it works.

I have a template class that sits between so

相关标签:
2条回答
  • 2021-02-12 12:00

    I think there is a better explanation why it is possible to do so than "because the standard says so":

    The reason it works is because pointers-to-members are constant values known at compile time (pointer-to-member is effectively an offset of a member from the start of a class). Thus they can be used as parameters of templates, just as any other integer constant can be.

    On the other hand, normal pointers are not compile time constants, because they depend on memory layout which only exists at runtime. They cannot be template arguments.

    0 讨论(0)
  • 2021-02-12 12:04

    When you ask a question along the lines of "why something works?", it implies that the fact that it works is somehow surprising to you. It is impossible to answer the question unless you explain why you find it surprising.

    Why it works? Because the language specification explicitly says that it shall work. There's no other answer, until you explain your concerns in more detail.

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