Tuesday, 19 July 2011

C++: Declaring a pointer to a template method

Busy writing some template gibberish, we needed to make a healthy trade in pointers to template-member-functions. Of template classes. (Where the template function parameters themselves were pointers to template methods on template classes, but let's not worry about that detail right now).

It took a little run-up to get the C++ syntax right, so I present it here for your viewing pleasure.

All code tested against g++ 4.2.1 only.

Case 1: Normal pointer to member

Let's just remind ourselves of the syntax for a simple pointer to (normal, non-template) member function:

Note: I've gratuitously changed the < < stream operators into "--" just to get the syntax through blogger's composer window. Sorry about that. I pray that no other C++ syntax was sacrificed in this publishing exercise
class Target1
{
public:
void Method(int a)
{
std::cout -- "Target1(" -- a -- ")\n";
}
};

void PointerToNormalMemberFunction()
{
Target1 target;
// This is how we construct a normal pointer to member function
void (Target1::*oneParam)(int) = &Target1::Method;
(target.*oneParam)(1);
}
Relatively simple.

Case 2: A pointer to template member function

Here's the first incursion of templates. If you're looking at a template method, this is how you'd declare your pointers to it:
class Target2
{
public:
template <typename T>
void Method(T a)
{
std::cout -- "Target2("--a--")\n";
}
};

void PointerToTemplateMemberFunction()
{
Target2 target;

// This is how we construct a pointer to a template member function
// See how the template type of the method is mentioned at the end of the method name.
void (Target2::*oneParamTemplateInt)(int) = &Target2::Method<int>;
void (Target2::*oneParamTemplateFloat)(float) = &Target2::Method<float>;
(target.*oneParamTemplateInt)(2);
(target.*oneParamTemplateFloat)(2.5);

// However, the compiler can deduce the template type of the method
void (Target2::*shorterInt)(int) = &Target2::Method;
void (Target2::*shorterFloat)(float) = &Target2::Method;
(target.*shorterInt)(3);
(target.*shorterFloat)(3.5);
}
Note that you can chose whether or not to specify the template types of the method when you assign it to your member-function pointer. The compiler can deduce these for you.

Case 3: Pointer to template methods with more than one template parameter

This is not significantly different from the above, we just extend the types in the pointer-to-member.

class Target3
{
public:
template <typenameT>
void Method(T1 a, T2 b)
{
std::cout -- "Target3("--a--","--b--")\n";
}
};

void PointerToTemplateMemberFunctionWithTwoParameters()
{
Target3 target;

// This is how we construct a pointer to a template member function
// with multiple template parameters. Just like above, really.
void (Target3::*oneParamTemplateIntFloat)(int,float) = &Target3::Method<int,float>;
void (Target3::*oneParamTemplateFloatInt)(float,int) = &Target3::Method<float,int>;
(target.*oneParamTemplateIntFloat)(4,4.5);
(target.*oneParamTemplateFloatInt)(4.5,4);

// Again, the compiler can deduce the type of the methods
void (Target3::*shorterIntFloat)(int,float) = &Target3::Method;
void (Target3::*shorterFloatInt)(float,int) = &Target3::Method;
(target.*shorterIntFloat)(5,5.5);
(target.*shorterFloatInt)(5.5,5);
}
Again, note, the compiler can generally deduce the correct template method without you having to specify the template parameter types.

Case 4: Pointer to template methods in a template class.

Now it's getting sillier - a pointer to a template method in a template class. the syntax does still make sense, it just depends how far down the rabbit hole you want to go.

template<typename TYPE>
class Target4
{
public:
Target4(const TYPE &value) : value(value) {}
TYPE value;

template <typename T>
void OneParam(T a)
{
std::cout -- "Target4::OneParam("--value--","--a--")\n";
}

template <typename T1, typename T2>
void TwoParam(T1 a, T2 b)
{
std::cout -- "Target4::TwoParam("--value--","--a--","--b--")\n";
}
};

void PointerToTemplateMemberInTemplateClass()
{
Target4<char> target('c');

void (Target4<char>::*oneParam)(float) = &Target4<char>::OneParam<float>;
(target.*oneParam)(6.5);

// Again, we can miss off the last template types
void (Target4<char>::*shorter)(float) = &Target4<char>::OneParam;
(target.*shorter)(6.75);

// Two parameters just extends the scheme
void (Target4<char>::*twoParam)(float,int) = &Target4<char>::TwoParam;
(target.*twoParam)(6.8,6);
}

Case 5: Using a pointer to a template method of a template class inside the template class itself

If you want to make use of a pointer to template method within a template class, you simply cannot specify the template method's parameter types. The compiler considers this a syntax error. So you have to rely on the compiler deducing the correct template method instantiation. (See edit below.)

In the case of this example, it copes fine. In more complex cases, it may hurt less if your call template method overloads different names.

template<typename TYPE>
class Target5
{
public:
Target5(const TYPE &value) : value(value) {}
TYPE value;

template <typename T>
void OneParam(T a)
{
std::cout -- "Target5::OneParam("--value--","--a--")\n";

typedef void (Target5<E>::*MethodTypeToCall)(T);
// Here, the compiler picks the right overload
MethodTypeToCall toCall = &Target5<E>::Private;
// In this case, the compiler does not let us write the following line (parse error):
//MethodTypeToCall toCall = &Target5<E>::Private<t;;
(this->*toCall)(a);
}

template <typename T1, typename T2>
void TwoParam(T1 a, T2 b)
{
std::cout -- "Target5::TwoParam("--value--","--a--","--b--")\n";

typedef void (Target5<E>::*MethodTypeToCall)(T1,T2);
MethodTypeToCall toCall = &Target5<E>::Private; // compiler picks the right overload
// you can't add the method's template parameters to the end of that line
(this->*toCall)(a,b);
}

private:

template <typename T>
void Private(T a)
{ std::cout -- "Target5::Private("--value--","--a--")\n"; }
template <typename T1, typename T2>
void Private(T1 a, T2 b)
{ std::cout -- "Target5::Private("--value--","--a--","--b--")\n"; }
};

void HoldingAPointerToTemplateMemberInTemplateClass()
{
Target5<r> target('c');

void (Target5<r>::*oneParam)(int) = &Target5<r>::OneParam;
(target.*oneParam)(7);
void (Target5<r>::*twoParam)(float,int) = &Target5<r>::TwoParam;
(target.*twoParam)(7.5,7);
}
Edit: it's been pointed to to me that you can name a specific overloaded template method using the following syntax. Add this to your pipe and smoke the whole template shenanigans:

MethodTypeToCall toCall2 = &Target5::template Private<T>;

This kind of template gibberish is why you know you love C++.

Simples, init?

The extra thing we added to all this syntactical joy was to have one of the template method's (template) parameter types itself a pointer to a template method on a template class.

It was at this point our brains dribbled out of our ears, and we had to retrace our template syntax steps back up this rabbit hole.

37 comments:

Sujit kUmar said...

Nice tutorial. Thanks for sharing the valuable info about c Training. it’s really helpful. Who want to learn c language this blog most helpful. Keep sharing on updated tutorials…..

Lars V said...
This comment has been removed by the author.
Lars V said...
This comment has been removed by the author.
venu puram said...

"C++: Declaring a pointer to a template method" Good Information and also C++ holds the best ever knowledge in Graduation period and is also an Important subject, When I was having my PMP Training in Chennai. I got some major projects related to C++ and also was willing to take part in C++ projects. Thank you for providing the information. Please keep updating

Anonymous said...

Can you do < (&_lt;) without the _ ?

Anonymous said...

Yep, so you can do:

cout << "string";

Remove the space from this: & lt;

aashutosh webtrackker said...

Aws online training in india
Salesforce online training in india

SAS Online Training in india

Salesforce admin online training in india

Linux Online training in India

aashutosh webtrackker said...

React.JS online training in india

Python online Training in India

Oracle DBA online training in India

Java online Training in India

SAP online Training In india

aashutosh webtrackker said...

Digital Marketing Online Training in India

Cloud Computing Online Training in India

Hadoop online training in INDIA

Javascript Training In Noida

Industrial Training in Noida

sravanthi said...

You’ve done a great job with this.Thanks to share this informative article.


Oracle Fusion Technical Training In Hyderabad

Richard Swayar said...

Australia Best Tutor is one of the best Online Assignment Help providers at an affordable price. Here All Learners or Students are getting best quality assignment help with reference and styles formatting.

Visit us for more Information

Australia Best Tutor
Sydney, NSW, Australia
Call @ +61-730-407-305
Live Chat @ https://www.australiabesttutor.com




Our Services

Online assignment help
my assignment help Student
Assignment help Student
help with assignment Student
Students instant assignment help
Students Assignment help Services

AutoCAD training in Noida said...

Each department of CAD have specific programmes which, while completed could provide you with a recognisable qualification that could assist you get a job in anything design enterprise which you would really like.

AutoCAD training in Noida

AutoCAD training institute in Noida


Best AutoCAD training institute in Noida

tanmay chaubey said...

If you want to join then you must join webtrackker technology which provides 100% placement.

servicenow training institute in Noida

ServiceNow portal Training in Noida

ServiceNow integration Training in Noida

ServiceNow implementation Training in Noida

servicenow scripting Training in Noida

Best servicenow admin training institutes in Noida


Best Servicenow Developer training training institute in Noida

tushar rana said...

6-week summer course in Noida - 6 weeks The summer course plays a crucial role in shaping the career of young aspiring / informatics students. This training has been specifically introduced so that students can become familiar with current industrial culture and industrial needs. Webtrackker technology offers a 6-month training program for students / graduates that includes small and large projects.
6-week summer course in Noida

raman rajput said...

hotels coupon codes

hotel offers & deals

hotels discount offers

nearbuy coupon codes

nearbuy promo codes

nearbuy deals and offers

nearbuy discounts

zoomcar promo code

zoomcar coupon code

zoomcar offers on ride

zoomcar deals and offers

raman rajput said...


healthkart deals and offers

healthkart discount offers

bigbasket promo codes

bigbasket coupon codes

bigbasket offers

bigbasket coupon and deals

pizzahut promo code

pizzahut coupon codes

pizzahut offers

pizzahut coupon and offers

hotels promo code

raman rajput said...

cleartrip coupon code

cleartrip offers and deals

cleartrip deals

MMT promo Codes

MMT coupon codes

Makemytrip promo codes

makemytrip offers

makemytrip deals & offers

healthkart coupon code

healthkart promo codes

Naveen k said...

Thanks for sharing this blog. This very important and informative blog Learned a lot of new things from your post! Good creation and HATS OFF to the creativity of your mind.
Very interesting and useful blog!
simultaneous interpretation equipment
conference interpreting equipment
tour guide system
silent disco headphones

Rohan kumar said...

Cloud Computing Training In Noida
Webtrackker is IT based company in many countries. Webtrackker will provide you a real time projects based training on Cloud Computing. If you are looking for the Cloud computing training in Noida then you can join the webtrackker technology.
Cloud Computing Training In Noida , Cloud Computing Training center In Noida , Cloud Computing Training institute In Noida ,

Company Address:
Webtrackker Technology
C- 67, Sector- 63, Noida
Email: info@webtrackker.com
Website: www.webtrackker.com
http://webtrackker.com/Cloud-Computing-Training-Institutes-In-Noida.php

Rohan kumar said...

Cloud Computing Training In Noida
Webtrackker is IT based company in many countries. Webtrackker will provide you a real time projects based training on Cloud Computing. If you are looking for the Cloud computing training in Noida then you can join the webtrackker technology.
Cloud Computing Training In Noida , Cloud Computing Training center In Noida , Cloud Computing Training institute In Noida ,

Company Address:
Webtrackker Technology
C- 67, Sector- 63, Noida
Email: info@webtrackker.com
Website: www.webtrackker.com
http://webtrackker.com/Cloud-Computing-Training-Institutes-In-Noida.php

prem said...

Video editing course in Noida
Video editing training institute in Noida- Webtrackker Technology is and IT Training institute providing the Video editing course in Noida, FCP, Final Cut Pro Training in Noida. For more call us- 8802820025.
Video editing course in Noida
best video editig course in noida
best video edtitng institute in noida
Company Address:
Webtrackker Technology
C- 67, Sector- 63, Noida
Phone: 01204330760, 8802820025
Email: info@webtrackker.com
Website: http://webtrackker.com/Best-training-institute-Video-editing-FCP-course-in-Noida.php

prem said...

Video editing course in Noida
Video editing training institute in Noida- Webtrackker Technology is and IT Training institute providing the Video editing course in Noida, FCP, Final Cut Pro Training in Noida. For more call us- 8802820025.
Video editing course in Noida
best video editig course in noida
best video edtitng institute in noida
Company Address:
Webtrackker Technology
C- 67, Sector- 63, Noida
Phone: 01204330760, 8802820025
Email: info@webtrackker.com
Website: http://webtrackker.com/Best-training-institute-Video-editing-FCP-course-in-Noida.php

bhavna webtrackker said...


rpa training institute in noida

Blockchain training institute in Noida

amarraj paindit said...

rpa training institute in noida
sas training institute in noida
hadoop training institute in noida
blokchain traninig institute noida


amarraj paindit said...

rpa training institute in noida
sas training institute in noida
hadoop training institute in noida
blokchain traninig institute noida


amarraj paindit said...

servicenow scripting Training in Noida
rpa training institute in noida
sas training institute in noida
hadoop training institute in noida
blokchain traninig institute noida


amarraj paindit said...

servicenow scripting Training in Noida
rpa training institute in noida
sas training institute in noida
hadoop training institute in noida
blokchain traninig institute noida


Arvind Rawat said...


Like different elements of India, numerous oil and spices usually cross into making food. This effects in substances getting caught to the partitions of the filter out.
Visit here
http://kitchenware.ml
Best kitchen chimney installation and service
Auto clean chimney sevice in Faridabad

Robotic Process Automation Tutorial said...

Very interesting blog.Thanks for sharing this much valuable information.Keep Rocking.
rpa training in chennai | rpa course fee in chennai | trending technologies list 2018

Aman CSE said...

Thanks For sharing such a wonderful Blog on RPA. This blog contains so much of data about RPA that anyone who is searching for RPA, its really helpful for them to grab this data from your blog on RPA. Again thank you so much for your blog on RPA.
Thanks and Regards,
blue prism training in chennai
Best blue prism training in chennai
blue prism training cost in chennai

Balaji said...

Very interesting blog.Thanks for sharing this much valuable information.Keep Rocking.

https://www.hopetutors.com/course/automation-anywhere-training-in-chennai/

Meera Kumar said...

I have read a few of the articles on your website now, and I really like your style. Thanks a million and please keep up the effective work.
R Programming Training in Chennai | R Programming Training in Chennai with Placement | R Programming Interview Questions and Answers | Trending Software Technologies in 2018 | R Programming Online Training course

kavinilavu G said...


Great efforts put it to find the list of articles which is very useful to know, Definitely will share the same to other forums. | Roles and reponsibilities of hadoop developer | hadoop developer skills Set | hadoop training course fees in chennai | Hadoop Training in Chennai Omr

kiran mai said...

You really did a great job. I found your blog very interesting and very informative. I think your blog is great information source & I like your way of writing and explaining the topics.

OpenShift Training

Pavan Kumar said...

I like the way you explain! Thanks for the great information, Pete.

Anexas Europe said...

Needed to compose you a very little word to thank you yet again regarding the nice suggestions you’ve contributed here
Machine Learning With TensorFlow Training and Course in Muscat
| CPHQ Online Training in Singapore. Get Certified Online

Afreen said...

CPHQ Online Training in Kabul. Get Certified Online
| CPHQ Training Classes in Al Farwaniyah