Pointer to class member as template parameter

Jonathan Sterling picture Jonathan Sterling · Jul 30, 2011 · Viewed 18.2k times · Source

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.

Answer

hammar picture hammar · Jul 30, 2011

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 { ... };