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.
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.
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.
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.
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 .
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 { ... };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With