Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.


Channels ▼
RSS

Conversations: Template Specializations, Default Parameters, and Other Fun Stuff


March 2002 C++ Experts Forum/Conversations


We watched the gate from a short distance, alert that the invaders might follow us through from the Europan base. It appeared, however, that the enemy was quite content to abandon us, or at least wait us out. The gate remained quiet.

Despite constant alertness, Goofies had got a couple of our sentries. We had killed many Goofies — sometimes with our conventional weapons, sometimes as tests of the alien artifacts, at least one of which spewed huge energy bolts that made it dangerous to aim at anything too close nearby — but the Goofies seemed to be in unlimited supply.

So it was that we were only partly surprised by the mutiny.


"Hey, Junior, how's it going?" I tensed at Bob's voice. But then it struck me — Bob was not his usual condescending self. He was almost... dare I say... civil.

"Not bad, Bob," I replied, turning to face him. We stared at each other for a moment.

"Uh, say, Junior, I was wondering if I could get a little help."

I was stunned. Speechless. Bob, the worst programmer in the department; the man who delighted in writing obscure, difficult to maintain code; the man whose arrogance was so thick you could smell it a block away; the man who stopped by my cubicle only long enough to dump his problems in my lap (and latte on my desk) was standing at my cubicle, asking me for help?

"Aaah, sure, Bob," I finally answered. "What's up?"

Bob sat himself down in the guest chair. "OK, here's the scoop. I've managed to condense it down to this source code." He took over on the keyboard and called up a file on my workstation. I looked closely at it:

#include <iostream>

template<typename T, std::size_t size = 10>
class c
{
  T m[size];
public:
  void print_size() 
  {
    std::cout << size << std::endl;
  }
};

template<> class c<char>
{
  char m[100];
public:
  void print_size()
  {
    std::cout << 100 << std::endl;
  }
};

int main()
{
  c<char>().print_size();
  c<char, 10>().print_size();
}

"First, I don't see how it can compile. I mean, I thought the template argument has to be a class or type name, not a... well, an ordinary parameter."

"You mean the size_t parameter?" I quizzed. Bob grunted, which I took to mean an affirmative. "Yeah, the first time I saw a non-type parameter, my brain stopped for a moment too. I was used to seeing class or typename declarations, not regular parameters. The Guru assured me that it was allowed, but she made me look it up in the Standard for myself. You can only use integral or enumeration types, pointers or references to objects or functions, or pointers to member [1]. In fact, with integral types, the parameter becomes an integral constant expression...."

"A whozer whatzit?" Bob interrupted.

"A compile-time constant," I translated from Standardese to English. "Anyway, since it's an integr— er, that is, since it's a compile-time constant, that allows you to use size to declare the array of T objects. Pretty nifty.

"Once I learned this, I was toying with the idea of using a template to provide a more flexible switch statement, something like," I opened a new text file and typed in:

template<int value1, int value2, int value3>
void f(int currentValue)
{
    switch(currentValue)
    {
    case value1:
        ...
    case value2:
        ...
    case value3:
        ...
    }
}
void g()
{
    f<1, 2, 3>(1); // executes value1 case
    f<2, 3, 1>(1); // executes value3 case
}

"I couldn't come up with a practical application for it, so I filed it in the 'nifty but no practical application for it' category..."

"Alongside other useless information that gets trotted out at parties, no doubt," Bob interrupted, glancing at his watch. "That's, uh, real interesting, Junior, but getting back to my problem," he reached over, closed my text window, and restored his original program. "See, when I compiled and ran this, the first template prints out 100, just like I thought it would, 'cause it um... instantiates the... uh.... specialization c<char>. I expected the second template to print out 10, because I figured it'd match up the 10 with the default parameter of 10, but it prints out 100 as well."

I studied the code. Bob sipped his latte.

"Well," I welled to fill in the silence, "My first reaction would be that I'd expect both templates to print out 10."

"Y'know, that's what I told Her Holine— uh, I mean, that's what I thought at first." Ah, that was a little more like the Bob I knew — he was about to call the Guru a nasty name.

"I try to think of default parameters as 'lazy shortcuts'," I continued. "Whenever I write something that takes advantage of default parameters, I have to remember that the compiler treats it as if I had actually written the parameter."

"I know that," Bob said impatiently. He took over the keyboard and modified the program slightly:

int main()
{
  c<char>().print_size();
  // compiler acts as if I'd written
  // c<char, 10>().print_size();

  c<char, 10>().print_size();
}

"This is an exact match for the base template. In that case, though, the program would print out 10 for each size, but it prints out 100, so what's going on?" Bob asked impatiently, glancing again at his watch.

I savored this moment. Not only was Bob aware that I knew something he didn't, but he was actually acknowledging it!

"That's not the only place the default parameter is used," I finally said. Bob gave me a quizzical look. "The specialization uses it, too." I took over the keyboard, after carefully moving Bob's latte out of the way. "The specialization that you wrote as..."

template<> class c<char>

"... acts as if you wrote:"

template<> class c<char, 10>

"So," I continued, "you have not specialized on c<char>, but on c<char, 10>, where the size template parameter is an integral constant-expression with the value 10. In other words, your program acts as if you had written:"

#include <iostream>
template<typename T, std::size_t size = 10>
class c
{
  T m[size];
public:
  void print_size() 
  {
    std::cout << size << std::endl;
  }
};
 
template<> class c<char, 10>
{
  char m[100];
public:
  void print_size()
  {
    std::cout << 100 << std::endl;
  }
};

int main()
{
  c<char, 10>().print_size();
  c<char, 10>().print_size();
}

"I get it," Bob smiled as he leaned back in his chair. "In main(), both instantiations of c instantiate the specialization." I didn't like the look of that smile on his face. He stood up, then in a louder tone of voice, he continued, "And remember, Junior, that default parameters apply to template specializations as well." I was puzzled by his sudden change. I spotted the Guru approaching, an open tome in her hand as usual.

She stopped in front of Bob. "Why are you interrupting my apprentice's devotions?" the Guru demanded.

"Hello, doll-face," Bob beamed at the Guru. "I was just explaining to Junior here, why the correct output of that program we were talking about is 100 100." He glanced at his watch. "Yep, coming up on two o'clock — I better get to Pete's office and go over this with him."

The Guru and I watched him disappear in the direction of Pete Williams's office. Pete was the new manager brought in when our company was acquired last month.

"Figured it out, did he?" the Guru murmured as she turned to me. "Now matters are worse." My stomach did a flip-flop.

"Um, what was that all about?" I asked.

The Guru sat down wearily in the guest chair. With Bob gone, she was back in "normal" mode. "You asked me once why Bob was still around, even though he's an..." I could see her struggling for words.

"Incompetent, arrogant, misogynistic... " I supplied, which the Guru capped with a word I would not care to repeat to my mother, even if she is stone deaf.

"Yes, exactly," the Guru continued, calmer now. "Bob was in quite tight with the previous upper management. He somehow had them hoodwinked into believing he's a... well, a golden boy. All my attempts to expose him for what he is were swept aside because he had the upper management convinced that I was still bitter about our divorce. As if!

"Anyway," she continued, "when we had our change in management, I saw a perfect opportunity. I convinced Pete Williams to pose him a challenging question, which I knew Bob would never figure out. Or so I thought. Pete agreed that the question I posed would be simple enough even for you to answer." I bristled at that, but the Guru, absorbed in her explanation, ignored me. "If Bob could not figure out the answer by two o'clock, Pete was going to keep a close eye on him, perhaps even put him on probation. Eventually, I'm sure I could have got Bob what he deserved — a pink slip. Now, though, it's going to be much harder."

She sighed and silently stood and glided away.

My stomach rose in my throat. "What have I done?" I muttered to myself.


It was just before daybreak that the conspirators acted. Several officers went armed into Da Rosa's tent, and we quickly discovered that only the mutineers' sergeants had functioning weapons. Da Rosa put up no real opposition; I think he was tired and already resigned to the fact that holding out further would be futile. He gave up his sidearm, Hinckel took command, and we prepared to surrender.

A man was sent to throw a surrender note through the gate. We could see a brief glimpse of movement through the gate as the note was retrieved and soon came the reply. Following instructions, we put down our weapons and filed through the gate one by one. When my turn came, I stepped through into the dimly lit Ballroom and turned to find myself staring at the business end of weapons carried by grim-faced men. I sighed and was bound like the others.

Note

[1] ISO C++ Standard, IOS/IEC 14882, clause 14.1 paragraph 4.

Acknowledgements

Thanks to Sergei ([email protected]...) for asking the question in comp.lang.c++ that inspired this article.

Jim Hyslop is a senior software designer at Leitch Technology International Inc. He can be reached at [email protected].

Herb Sutter (<www.gotw.ca>) is an independent consultant and one of the instructors of The C++ Seminar (<www.gotw.ca/cpp_seminar>). He is also secretary of the ISO/ANSI C++ standards committee and author of the acclaimed books Exceptional C++ and More Exceptional C++.


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.