Pointer to class member as template parameter
Asked Answered
F

1

41

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.

Faline answered 30/7, 2011 at 3:2 Comment(0)
A
60

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 { ... };
Appreciate answered 30/7, 2011 at 3:7 Comment(7)
Thanks! I can further generalize this as template <class A, class B, A B::*member>, which is useful to me. I suppose I should have read that section of the standard a bit closer.Faline
Is there any way that the first two arguments A and B could be left out?Brawl
@Brawl See proposal N3601. via #15149249Brentonbrentt
any way to pass in a class method?Repast
@Repast There is no separate thing such as method in C++. type of pointer to function includes member functions.Hartsfield
As I understand , it's available in c++ since first template appearance.Neoplasticism
And in C++20 (maybe earlier) you can now do template <auto member_ptr> too!Contraband

© 2022 - 2024 — McMap. All rights reserved.