C ++ Templates with pointer to member function of signature and type

The code below works fine, but I cannot figure out at what points of the C ++ standard it should be valid.

template< class C, class signature > void f(signature C::*ptr) { } 

When C = A and signature = void(float, int) , the function f will

 void f(void(A::*ptr)(float, int)) 

On the basis of what parts of the standard does the template apply to the latter?

+5
source share
1 answer

Better go through it one at a time. To avoid ambiguities, I will use different template argument names in the example

 template<class C, class signature> void f(signature C::*ptr) {} 

All citations refer to the latest working draft of the C ++ 14 standard.

First we need to understand how template parameters are handled.

[temp.param] / 3 A type parameter whose identifier does not follow the ellipsis defines its identifier will be the name typedef

So, your template definition has two parameters, T and signature. When using signature in the template body, it is therefore equivalent to typedef

 typedef void signature(float, int); 

This typedef can be used to declare a function pointer parameter, as in your example:

[dcl.fct] / 12 A typical function type may be used to declare a function, but should not be used to define a function

In the parameters of the template function, you write signature T::*ptr , let's see what the standard says about member pointers:

[dcl.mptr] / 1 In a TD declaration, where D is of the form

 nested-name-specifier * attribute-specifier-seq_opt cv-qualifier-seq_opt D1 

and the naming specifier denotes the class, and the identifier type in the declaration T D1 is the derived-declarator-type-list T, then the identifier type D is equal to result-declarator-type-list cv-qualifier-seq pointer to the class member the nested qualifier name type T.

In our example, T is signature , the typedef function and D is C::*ptr .

This explains what types the compiler will output for example.

 void f(void(A::*ptr)(float, int)); 
+4
source

All Articles