Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer to class member as template parameter

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.

like image 531
Jonathan Sterling Avatar asked Jul 30 '11 03:07

Jonathan Sterling


People also ask

Can template be a pointer?

A template has only one type, but a specialization is needed for pointer, reference, pointer to member, or function pointer types. The specialization itself is still a template on the type pointed to or referenced.

Which is correct example of template parameters?

For example, given a specialization Stack<int>, “int” is a template argument. Instantiation: This is when the compiler generates a regular class, method, or function by substituting each of the template's parameters with a concrete type.

Can we pass Nontype parameters to templates?

Template non-type arguments in C++It is also possible to use non-type arguments (basic/derived data types) i.e., in addition to the type argument T, it can also use other arguments such as strings, function names, constant expressions, and built-in data types.

How do I create a pointer to a member in C++?

The pointer to member operators . * and ->* are used to bind a pointer to a member of a specific class object. Because the precedence of () (function call operator) is higher than . * and ->* , you must use parentheses to call the function pointed to by ptf .


1 Answers

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 { ... }; 
like image 67
hammar Avatar answered Sep 18 '22 20:09

hammar