Pointer to class member as template parameter

20,395

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 { ... };
Share:
20,395
Jonathan Sterling
Author by

Jonathan Sterling

type theorist

Updated on July 09, 2022

Comments

  • Jonathan Sterling
    Jonathan Sterling almost 2 years

    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.

  • Jonathan Sterling
    Jonathan Sterling almost 13 years
    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.
  • user1158559
    user1158559 over 10 years
    Is there any way that the first two arguments A and B could be left out?
  • underscore_d
    underscore_d over 8 years
    @user1158559 See proposal N3601. via stackoverflow.com/questions/15148749/…
  • xaxxon
    xaxxon about 8 years
    any way to pass in a class method?
  • Swift - Friday Pie
    Swift - Friday Pie over 7 years
    @xaxxon There is no separate thing such as method in C++. type of pointer to function includes member functions.
  • Кое Кто
    Кое Кто over 5 years
    As I understand , it's available in c++ since first template appearance.
  • Thomas Eding
    Thomas Eding over 2 years
    And in C++20 (maybe earlier) you can now do template <auto member_ptr> too!