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 { ... };
Comments
-
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 almost 13 yearsThanks! 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 over 10 yearsIs there any way that the first two arguments A and B could be left out?
-
underscore_d over 8 years@user1158559 See proposal N3601. via stackoverflow.com/questions/15148749/…
-
xaxxon about 8 yearsany way to pass in a class method?
-
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 yearsAs I understand , it's available in c++ since first template appearance.
-
Thomas Eding over 2 yearsAnd in C++20 (maybe earlier) you can now do
template <auto member_ptr>
too!