C++ Templates: Partial Template Specialization

Share the Article

Partial template specialization means, rewriting C++ templates by explicitly specifying a few but not all of the template parameters. Now, when such specializations are available, the compiler shall call these specialized template version on argument match only. Specifically, it no longer calls the main template. This is also a form of compile-time polymorphism.

The following program shows this:

#include <iostream> //main header using namespace std; //namespace //Main Template. template<typename TT1, typename TT2> //Two types class TestHash { TT1 key; TT2 value; public: TestHash() { cout << "Main Template Constructor" << endl; } }; //Partial Template Specialization. template<typename TT2> //Note : only one type class TestHash<int, TT2> { int key; TT2 value; public: TestHash() { cout << "Partial Specialization Constructor" << endl; } }; //Full Specialization. template<> //Note : no type needed class TestHash<int, float> { int key; float value; public: TestHash() { cout << "Full Specialization Constructor" << endl; } }; int main() { TestHash<char, std::string> th1; TestHash<int, std::string> th2; TestHash<int, float> th3; return 0; }

The output of above program is:

Main Template Constructor Partial Specialization Constructor Full Specialization Constructor

Here, initialization of TestHash with “th2” calls the Partial Specialization, because the first template parameter “int” has a perfect match.

Missing Functions in Specialization

In any member function is missing in template specialization (either partial or full), then an object based on specialization will not be able call. However, objects based on main template will be able to call. In following code, the same class “TestHash” has a function “printStatus” missing in specialization.

#include <iostream> //main header using namespace std; //namespace template<typename TT1, typename TT2> class TestHash { TT1 key; TT2 value; public: TestHash() { cout << "Main Template Constructor" << endl; } void printStatus() //this is available only here { cout << "This is main template" << endl; } }; template<typename TT2> class TestHash<int, TT2> { int key; TT2 value; public: TestHash() { cout << "Partial Template Constructor" << endl; } }; int main() { TestHash<char, std::string> th1; TestHash<int, std::string> th2; th1.printStatus(); //th2.printStatus(); //This will generate error return 0; }

Output:

Main Template Constructor Partial Template Constructor This is main template

On uncommenting the “h2.printStatus()” line, the compiler will produce following error:

compiler error due to usage of missing function in partial C++ template

Uses of Partial Template Specialization

The implementation of std c++ functions which differentiate between types is generally done by using partial specialization.

For instance,

  • std::is_reference,
  • std::is_lvalue_reference,
  • std::is_rvalue_reference,
  • std::is_pointer

These are using this c++ feature to achieve the desired goal indeed.

Basic implementation for “is_pointer”

template<typename T> class is_this_pointer { public: enum { type=0 }; }; template<typename T> class is_this_pointer<T*> //Partial Specialization, T is type { public: enum { type=1 }; };
Example with datatypes

The following code snippet uses the above implementation directly passing type

cout << "int : " << is_this_pointer<int>::type << endl; cout << "int* : " << is_this_pointer<int*>::type << endl; cout << "int**: " << is_this_pointer<int**>::type << endl;

The output is:

int : 0 int* : 1 int**: 1
Example with pointers:
int const *pp = 0; int const **pq = &pp; int const *pr = px; cout<<"decltype(pp):"<<is_this_pointer<decltype(pp)>::type<< endl; cout<<"decltype(pq):"<<is_this_pointer<decltype(pq)>::type<< endl; cout<<"decltype(pr):"<<is_this_pointer<decltype(pr)>::type<< endl;

The output is:

decltype(pp) : 1 decltype(pq) : 1 decltype(pr) : 1
Example with variables (not pointers)
int ia; int &ib=ia; int &&ic=9; cout<<"decltype(ia) :" << is_this_pointer<decltype(ia)>::type << endl; cout<<"decltype(ib) :" << is_this_pointer<decltype(ib)>::type << endl; cout<<"decltype(ic) :" << is_this_pointer<decltype(ic)>::type << endl;

The output is:

decltype(ia) :0 decltype(ib) :0 decltype(ic) :0

Partial Specialization for function templates

In particular, C++ do not allow partial specialization for function templates. Instead, the program should use function overloading to use the right implementation.

Main Funda: Partial template specialization takes responsibility to handle a subset of scenarios

Related Topics:

 What are the drawbacks of using enum ?
Which member functions are generated by compiler in class?
How to stop compiler from generating special member functions?
Compiler Generated Destructor is always non-virtual
How to make a class object un-copyable?
Explaining C++ casts
How pointer to class members are different ?
How std::forward( ) works?
Rule of Three
How std::move() function works?
What is reference collapsing?
How delete keyword can be used to filter polymorphism
Copy Constructor and Move Constructor: Test with vector


Share the Article

2,731 thoughts on “C++ Templates: Partial Template Specialization

  1. I just could not depart your web site prior to suggesting that I actually loved the standard information an individual provide on your guests? Is gonna be back incessantly in order to check out new posts

  2. Hello! I could have sworn I’ve been to this blog before but after browsing through some of the post I realized it’s new to me. Anyways, I’m definitely happy I found it and I’ll be book-marking and checking back frequently!

  3. When I read an article on this topic, bitcoincasino the first thought was profound and difficult, and I wondered if others could understand.. My site has a discussion board for articles and photos similar to this topic. Could you please visit me when you have time to discuss this topic?

  4. This blog is definitely rather handy since I’m at the moment creating an internet floral website – although I am only starting out therefore it’s really fairly small, nothing like this site. Can link to a few of the posts here as they are quite. Thanks much. Zoey Olsen

  5. It’s too bad to check your article late. I wonder what it would be if we met a little faster. I want to exchange a little more, but please visit my site slotsite and leave a message!!

  6. Everything what you want to know about pills. Comprehensive side effect and adverse reaction information.
    online generic cialis
    Everything what you want to know about pills. Everything what you want to know about pills.

  7. Hey there just wanted to give you a quick heads up. The text in your article seem to be running off the screen in Opera. I’m not sure if this is a formatting issue or something to do with web browser compatibility but I thought I’d post to let you know. The design and style look great though! Hope you get the issue solved soon. Many thanks

  8. naturally like your website but you have to take a look at the spelling on several of your posts. Many of them are rife with spelling problems and I in finding it very troublesome to inform the truth on the other hand I’ll certainly come back again.

  9. best cialis online 18 In view of the strong evidence that small doses of the aldosterone blockers spironolactone and eplerenone can protect vulnerable patients 19, 20 and significantly reduce blood pressures resistant to 3 drugs, 21 a logical way to provide maximal antihypertensive efficacy and to prevent hypokalemia might be a combination of chlorthalidone and spironolactone 12

  10. I’m not sure why but this web site is loading
    very slow for me. Is anyone else having this issue or is it a problem on my end?
    I’ll check back later and see if the problem still exists.

  11. The lower tier races, called claiming races, are where most of the accidents happen lasix Tick paralysis is a reversible disorder characterized by ascending motor weakness and flaccid paralysis

  12. Jason Missiaen, 23 years old and 6 foot 8, will serve as Henrik LundqvistГў s backup in New Jersey 40 mg lasix Nine weeks later, our OBGYN said I had a 50 chance of miscarriage, and sure enough, three weeks later, I miscarried our first baby

  13. viagra in spanish Recent data from a civilian trauma center in Southern California suggest that Gram negatives frequently are susceptible to third generation cephalosporins, carbapenems, and quinolones, while enterococci frequently are susceptible to penicillins in such cases

  14. tamoxifen citrate 20mg Criminal charges against some of the companies involved are possible and we can t help being reminded of our own warnings about the dangers of herbal and dietary supplements, so often assumed by customers to be harmless because they are natural, but potentially dangerous in combination with other medications

  15. Indeed, several studies have highlighted the unreliability of Cre LoxP recombination reporters, reporting discrepancies between multiple reporter alleles and target allele recombination 4, 6 nolvadex However, there are possible risks of which patients should be aware before beginning treatment

  16. tested, whether the simultaneous inhibition of both p53 antagonists, MDM2 and Wip1, induce p53 activation more potently than single inhibitors buy cialis online us General sensitivity loss on SWAP tests with strong dependency on duration and dose of tamoxifen, however, suggests that SWAP changes may occur early after tamoxifen utilization

  17. I like the valuable information you provide for your article. I’ll make a favorite on your blog and check it out here once more often. I’m rather sure I’ll hear a lot of new things. Let’s do it right here! Good luck to the next people! https://totovi.com/

  18. If you are looking for an article writer for your site, please let me know. You have a really good position and I think I’ll be a good asset. If you want to ease the burden a little, I’d like to use materials for your blog in exchange for returning the link to my blog. Please send me an email if you are interested. Thank you. I didn’t think of this, but it’s amazing! I’ve written several posts similar to this, but please come and see them! https://totoguy.com/

  19. An intriguing discussion is definitely worth comment. I do believe that you should publish more about this issue, it may not be a taboo subject but typically people don’t talk about such subjects. To the next! Many thanks!

  20. Good post. I learn something totally new and challenging on websites I stumbleupon every day. It’s always interesting to read through content from other writers and practice something from their sites.

  21. I seriously love your blog.. Great colors & theme. Did you make this web site yourself? Please reply back as I’m hoping to create my own website and would like to know where you got this from or what the theme is called. Thank you.

  22. This is the right blog for anyone who wishes to find out about this topic. You realize a whole lot its almost hard to argue with you (not that I really would want to…HaHa). You definitely put a brand new spin on a topic that has been discussed for ages. Great stuff, just excellent.

  23. Having read this I believed it was extremely informative. I appreciate you spending some time and energy to put this information together. I once again find myself spending a lot of time both reading and leaving comments. But so what, it was still worthwhile!

  24. That is a great tip particularly to those fresh to the blogosphere. Short but very accurate info… Appreciate your sharing this one. A must read post!

  25. You made some decent points there. I checked on the internet to learn more about the issue and found most people will go along with your views on this site.

  26. An impressive share! I have just forwarded this onto a coworker who was conducting a little homework on this. And he actually bought me breakfast because I discovered it for him… lol. So let me reword this…. Thanks for the meal!! But yeah, thanks for spending the time to talk about this subject here on your web site.

  27. When I initially left a comment I seem to have clicked on the -Notify me when new comments are added- checkbox and from now on every time a comment is added I receive four emails with the same comment. There has to be a means you can remove me from that service? Cheers.

  28. I am sorry. Ofteh iuse to rite by smartphone so it is difficolt to care my posts. Thanks ciniantoIt’s wonderful that you are getting thoughts from this articleas wellas from our discussion made at this time.

  29. You’ve made some really good points there. I checked on the web for more information about the issue and found most individuals will go along with your views on this website.

  30. Good day! I could have sworn I’ve visited this blog before but after looking at many of the posts I realized it’s new to me. Anyways, I’m certainly delighted I discovered it and I’ll be book-marking it and checking back frequently.

  31. May I simply say what a comfort to find someone that actually understands what they are talking about on the internet. You certainly understand how to bring an issue to light and make it important. More and more people should read this and understand this side of the story. I was surprised you are not more popular given that you certainly possess the gift.

  32. The next time I read a blog, Hopefully it won’t disappoint me as much as this particular one. After all, I know it was my choice to read through, but I actually thought you would probably have something interesting to say. All I hear is a bunch of complaining about something you could fix if you weren’t too busy searching for attention.

  33. I must thank you for the efforts you have put in writing this website. I really hope to see the same high-grade blog posts from you later on as well. In truth, your creative writing abilities has inspired me to get my very own blog now 😉

  34. hello there and thanks on your information – I’ve definitely picked up something new from right here. I did alternatively expertise some technical issues the usage of this web site, since I experienced to reload the site lots of occasions previous to I may get it to load properly. I have been pondering in case your web hosting is OK? Not that I am complaining, but sluggish loading circumstances instances will very frequently affect your placement in google and can harm your high quality score if ads and ***********|advertising|advertising|advertising and *********** with Adwords. Anyway I’m adding this RSS to my email and can look out for a lot extra of your respective exciting content. Make sure you replace this again very soon..

  35. The very next time I read a blog, Hopefully it does not fail me as much as this one. I mean, I know it was my choice to read, but I truly believed you’d have something interesting to say. All I hear is a bunch of complaining about something that you can fix if you weren’t too busy looking for attention.

  36. Hello there! This post couldn’t be written any better! Reading through this article reminds me of my previous roommate! He always kept preaching about this. I most certainly will send this information to him. Pretty sure he’ll have a great read. Thank you for sharing!

  37. silagra caravelair allegra home 560 preis At a demonstration in London on Wednesday, doctors used the new knife Гў which resembles a fat white pen Гў to slice into slabs of pig s liver buy cialis 5mg online Then there was another huge pain in the back, and Frey s huge body flew out of the smoke and fell heavily to the ground

  38. I have seen a lot of useful issues on your internet site about pcs. However, I’ve the viewpoint that laptops are still not nearly powerful sufficiently to be a good choice if you typically do jobs that require many power, such as video enhancing. But for web surfing, statement processing, and many other typical computer functions they are all right, provided you may not mind small screen size. Appreciate sharing your notions.

  39. Spot on with this write-up, I absolutely think this site needs much more attention. I’ll probably be back again to read more, thanks for the information.

  40. Our results thus demonstrate the integral role of a previously unrecognized functional crosstalk between HNK and Stat3 miR 34a and Wnt1 MTA1 ОІ catenin axes hims vs viagra Secondary end point was radiological response as measured by magnetic resonance imaging MRI, mammography and or ultrasound

  41. The pathologist also identifies if HER2 is overexpressed by assigning a number from 0 to 3, with 0 indicating HER2 isn t overexpressed and 3 denoting it s overexpressed in more than 30 of cancer cells clomid twins Wilson, USA 2022 06 18 16 59 28

  42. I loved up to you’ll receive performed right here. The comic strip is tasteful, your authored subject matter stylish. however, you command get got an nervousness over that you want be handing over the following. sick without a doubt come more formerly again since precisely the similar just about a lot incessantly within case you defend this increase.

  43. An impressive share! I have just forwarded this onto a colleague who has been conducting a little homework on this. And he in fact ordered me lunch due to the fact that I stumbled upon it for him… lol. So let me reword this…. Thank YOU for the meal!! But yeah, thanx for spending some time to discuss this issue here on your web page.

  44. I seriously love your website.. Excellent colors & theme. Did you build this amazing site yourself? Please reply back as I’m hoping to create my own website and would love to know where you got this from or what the theme is called. Many thanks!

  45. Oh my goodness! Impressive article dude! Thank you, However I am experiencing troubles with your RSS. I don’t understand why I am unable to join it. Is there anybody else having identical RSS issues? Anyone that knows the answer can you kindly respond? Thanks!

  46. Hello, There’s no doubt that your blog may be having internet browser compatibility issues. Whenever I look at your website in Safari, it looks fine however when opening in IE, it’s got some overlapping issues. I just wanted to give you a quick heads up! Aside from that, wonderful website.

  47. Having read this I believed it was rather enlightening. I appreciate you finding the time and energy to put this short article together. I once again find myself spending a significant amount of time both reading and leaving comments. But so what, it was still worthwhile!

  48. Your style is very unique in comparison to other people I’ve read stuff from. I appreciate you for posting when you have the opportunity, Guess I’ll just bookmark this web site.

  49. Slot pg เว็บตรง ค่ายเกมสุดฮอตตลอดหลายปีที่ผ่านมาที่เว็บ PG-SLOT.GAME ของเราให้วคามไว้วางใจในคุณภาพที่ดีที่สุดตลอดมา กับเกมสล็อตออนไลน์แตกง่าย ภาพคมกริบ แสงสีสวยงาม

  50. viagra differin cream uses So far, the FAA has banned use of portable devices in flight unless airlines have determined they don t pose a hazard does doxycycline treat uti In Japan for example, breast cancer was rare, but Japanese women who migrated to this country soon had the same rate of cancer as American women at least 400 higher that in Japan

  51. Your style is unique in comparison to other folks I have read stuff from. Many thanks for posting when you’ve got the opportunity, Guess I’ll just bookmark this blog.

  52. Can I simply say what a comfort to find somebody that genuinely knows what they’re discussing on the net. You certainly understand how to bring a problem to light and make it important. More and more people ought to check this out and understand this side of the story. I can’t believe you are not more popular since you certainly possess the gift.

  53. When I originally commented I appear to have clicked the -Notify me when new comments are added- checkbox and now every time a comment is added I recieve 4 emails with the same comment. Is there a means you can remove me from that service? Kudos.

  54. สล็อตออนไลน์ ยอดฮิตกับ PGSLOT-TH.COM เว็บสล็อตน้องใหม่เว็บตรง แตกง่าย ปลอดภัย สะดวกเล่นได้ทุกที่ทุกเวลา ไม่ผ่านเอเยนต์ รวยทางลัดได้ง่ายๆ สนุกจนลืมเวลาก็ PG SLOT

  55. Hi, There’s no doubt that your site may be having browser compatibility issues. When I look at your website in Safari, it looks fine but when opening in I.E., it has some overlapping issues. I merely wanted to provide you with a quick heads up! Other than that, fantastic website.

  56. An intriguing discussion is definitely worth comment. I do believe that you ought to write more on this subject matter, it might not be a taboo subject but typically people don’t talk about these subjects. To the next! Kind regards.

  57. The next time I read a blog, Hopefully it doesn’t disappoint me just as much as this one. After all, I know it was my choice to read, however I really believed you would have something helpful to talk about. All I hear is a bunch of whining about something that you could fix if you weren’t too busy seeking attention.

  58. I must thank you for the efforts you have put in writing this website. I really hope to check out the same high-grade blog posts from you later on as well. In truth, your creative writing abilities has encouraged me to get my very own site now 😉