Pointer to class member as template parameter

2020-02-18 12:21发布

问题:

Is it possible to have non-type template parameter which is actually a pointer to a class member? What I'm looking to do is something like the following:

struct Person {
  Dog dog;
};

template <?? ptr>
struct Strange {
  // ...
};

typedef Strange<&Person::dog> weird;

My work so far leads me to believe that nothing of the sort is possible, but I'm curious if anyone has can say otherwise.

回答1:

From the standard:

A non-type template-parameter shall have one of the following (optionally cv-qualified) types:

  • integral or enumeration type,
  • pointer to object or pointer to function,
  • reference to object or reference to function,
  • pointer to member.

So it is allowed, and seems to work on g++ like this:

template <Dog Person::*ptr>
struct Strange { ... };