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: Manipulations


April 2001 C++ Experts Forum/Conversations


That day began much like all other days.

I got up early to catch up on some technical reading, ate in the mess hall, and was five minutes early for my watch. The watch itself was routine and uneventful until nearly the end. Then, about ten minutes ahead of time, Brzenkowski wandered in for the next watch.

I suppose that was really the first odd thing, because Brzenkowski was never early for anything. I didn't think anything of it at the time, though. He looked at a few things and then walked over and said: "Hey. Frenell wants a minute of your time. You should drop by her stateroom on the way down."

"Oh? What's on?"

"Dunno," Brzenkowski shrugged. Then he smiled a little and clapped me on the back. "You might as well get out of here," he added. "I relieve you."

"Your watch," I agreed, signed off, and headed out and down.

When I got to Frenell's stateroom, the door was already open. She waved me inside, and the door slid shut behind us. There was another man sitting in her visitor's chair. I didn't remember seeing his face before.

"Hi, hi," he said in a friendly voice, standing to take my hand.

"This is Major Gilb," Frenell introduced us, and we sat.

"In understand you're available to help us out in the dome?" Gilb asked directly.

I glanced at Frenell. "Sure. If my skills fit."

"Oh, I think they will," Gilb assured me. "You worked with Jeannine Carruthers, didn't you? Yes, she works in my department now, and she speaks highly of you. Yes, quite highly. Now, I know you're doing more day-to-day work at the moment," he continued, "but this would be a bit more in the research area. Interested? Yes?"

"Sure. That would be nice. I've asked for some more research-oriented work anyway."

"Good. Good, I think that will fit the bill nicely. Yes, nicely. You understand of course that you'll need to stay for a time, at least until we get things well enough repaired to resume regular travel between these buildings and the dome? Don't want to use the transit tunnel more than we need to."

He began to ask me many things. I don't remember everything he said. My mind drifted, and among other things, I was thinking that it would be good to see Jeannine again. Funny, I thought, it's not like I'm a young buck with a new girlfriend. Not like it had been, on my first job, many years ago...


"There has to be a better way," I muttered.

"Hey, pardner, how's it going?" Wendy's cheerful voice floated over the cubicle wall. I stretched and decided it was a good time to take a break from my code, so I gophered up.

"Pretty good," I replied. "You back already? I thought you were going to be out for two weeks?"

That earned me a sideways glance. "Where've you been, on Jupiter? I was on training for two weeks and then took another week holiday!"

"Time flies when you're having fun," I allowed a devilish smile to sneak its way onto my mouth.

"Hmmph," she hmmphed. "You've been hanging out with Anna! See? I told you going to the Guru's party would be fun. Not that I expected you to go out with her daughter."

"Hey, I didn't know she was the Guru's daughter for a few weeks," I protested. "I thought she was just another party guest."

"You can tell me all about it over lunch." She tucked her rain boots under her desk and slipped on a pair of shoes. "So, how's it been going around here? You were looking a little intense when I came in."

"Yeah, pull up a chair and I'll fill you in on the gory details. You might have some fresh ideas." I dropped back into my seat as Wendy came into my cubicle.

"I implemented some of the communications functionality on our new system. It's a pretty simple protocol. Basically the server just responds with a series of comma-delimited, quoted strings. The strings can contain quotation marks, so I wrote a simple function that takes a string, wraps it with quotation marks, and escapes any embedded quotation marks, like this," I demonstrated on the whiteboard:

Input Output
field 1 "field 1"
field "with quotes" "field \"with quotes\""

"I wrote two functions, one to add the quotes, and another to strip them:"

std::string quote(const std::string &);
void f(std::ostream &o)
{
    o << quote("whatever");
}

std::string unQuote(std::string &);
void g(std::istream &i)
{
   std::string input;
   i >> input;
   std::string original=unQuote(input);

   // use string 'original' ...
}

"OK, that sounds straightforward," Wendy replied. "Your typical text file parser stuff."

"Right, that was pretty easy. But if the original string is large, then I end up making a copy of the entire string. Our server software has to be pretty tight, running on those boxes we're making. Also, some of the other project members complained that it was a little awkward to use, and they wanted to be able to use it with stream insertion and extraction, like this," I squeezed some more code onto my whiteboard:

std::string message;
// aStream is an istream subclass
aStream >> message;

"Somehow I have to take the text stream in aStream and extract one field into message. I've been playing with the stream buffers to see if that would work, but it's looking pretty ugly."

"Manipulators." Wendy and I jumped yet again at the Guru's soft voice.

"Beg pardon?" I asked.

"Write your own IOStream manipulators, as Langer and Kreft described in C++ Report a while back [1]."

"Uh, don't you mean the prophets Langer and Kreft?" I asked.

"Bob's in a meeting, and I don't have the energy for the Guru thing right now," she shrugged. Even though she wasn't in her Guru act, I still couldn't help but think of her as 'The Guru'. And she still managed to sneak up at the right moment! I was beginning to wonder if she had hidden a spycam somewhere.

"Ah," I said, wondering how come my replies always seemed so lame. "So how do you write an IOStream manipulator?"

"There are two approaches, depending whether you're implementing a manipulator with arguments or without. You need to implement one with arguments, so that's all I'm going to describe for you. If you want to know how to implement a manipulator without arguments, you'll have to read the back issue.

"Implementing an IOStream manipulator that takes arguments is actually pretty easy. You simply create a class that takes the appropriate arguments in its constructor, and provide an insertion or extraction operator that calls member functions on the manipulator. For example, suppose you want to write an ostream manipulator that manipulates an integer, you'd do this." The Guru erased my chicken scratches and wrote neatly in her fine, spidery script:

class myManipulator
{
    int manipValue;
public:
    explicit myManipulator(int i) : manipValue(i) {} // Note it's 'explicit'!
    friend ostream & operator <<(ostream &os, const myManipulator &mm);
};

"Using the manipulator is quite simple, as simple as using std::setfill or std::width:"

std::cout << myManipulator(42);

"The compiler will create a temporary, unnamed object of type myManipulator, and initialize it with the value 42. The compiler then invokes the overloaded insertion operator. The insertion operator performs the necessary manipulations on the stream, say something like this:"

ostream & operator <<(ostream &os, const myManipulator &mm)
{
    if (mm.manipValue == 42) {
        os << "Life, the universe, and everything";
    } else {
        os << "What was the question, again?";
    }
    return os;
}

I thought about it for a moment. "So... " I began cautiously, "my ostream manipulator would perform the character escaping and unescaping?"

"You could do that, or you could implement it as two separate classes, escape and unescape [2]." She paused suddenly, and a subtle change came over her. Just then, Bob walked past, on his way to the coffee station. "Remember, my child," the Guru continued, "to read and meditate on the writings of the prophets Kreft and Langer."

"Yes, my master, I will show you my writings this afternoon" I replied. Bob stopped in his tracks, dropping his latté cup on the carpeted floor. He picked up his cup and, without looking back, continued on. After he was out of sight, Wendy, the Guru, and I exchanged a three-way high five. Well, we tried to, that is.


Major Gilb didn't have much to cover, at least not immediately. Soon he wound down and said: "Yes. Yes, you'll be fine. Welcome to the team."

We shook hands, and I grinned. "Thanks. When will I be reassigned?"

"What? Oh, you already are. Don't worry about packing. Your things are already in the dome. They were moved while you were on watch; it's all right."

Before I could quite recover from that, I was taken along and presently found myself in a car that had been waiting in the transit station. While Gilb was still making cheerful small talk, its door closed, and we accelerated into the tunnel in the direction of the dome.

Notes

[1] Klaus Kreft and Angelika Langer. "Effective Standard C++ Library", C++ Report, April 2000.

[2] A complete, working example of the narrator's manipulators is available on the CUJ website at hyslop.zip.

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

Herb Sutter is an independent consultant and secretary of the ISO/ANSI C++ standards committee. He can be reached at [email protected].


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.