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

Inline Containers for Variable Arguments


September 1998/Inline Containers for Variable Arguments

The need to pass a variable number of arguments to a function (sometimes all arguments of the same type) arises often in C/C++ programming. The common approaches are to use the variable-argument feature of C/C++ or to pass a pointer to a constant-length vector along with its length (or a pointer past its end, STL-style). The variable arguments approach has the obvious disadvantages of being type unsafe and error prone, plus requiring you to establish a convention about the number and types of parameters. The second approach is better with regard to safety, but requires much code to be written for simple tasks. For instance:

int a, b, c;
//...
const int parms[] = { a, b, c };

// assume extern int
// f(int *From, int *To)
int M =
  f(parms,
    parms +
      sizeof(parms)/sizeof(*parms));

While this works, I find it unnecessarily verbose for what it does. I want a simple one-line construct to call a function with the number of arguments I need. Ideally the call would look like f(a), f(a, b), f(a, b, c), and so forth (which, alas, is not doable in a generic and safe way in C++). Taking an idea from Mr. Zlatko Marcok's article "Dynamic Arrays with Expression Templates," (CUJ, July 1998) I've put in place a simple mechanism that enables creation of "inline containers" of arbitrary length in an efficient, type-safe, and generic manner. They are intended to provide handy temporary objects, which will enable you to write:

int a, b, c;
//...
// assume extern int
// f(const std::vector<int> &v)
int M = f(make_vector(a)(b)(c));

I find this much more convenient and general. This syntax works for any number of arguments. It does not imply inefficient copying or spawning of temporaries. Plus, it's generic! The following also works:

double d, e, f;
//...
// assume extern double
// f(const std::vector<double> &v)
double M = f(make_vector(d)(e)(f));

It works because make_vector is a template function. For all these reasons, I find this approach very elegant and useful, especially when passing a variable number of arguments of the same type to a function. I have also provided functions make_list and make_deque built on the same codebase.

The implementation is simple: I derive a new class from the container of choice (default: vector) and define only two constructors for it. I also overload the operator() member. operator() appends an element to the container and returns a reference to it, so calls to that operator can be chained. This is the whole wizardry. I have also given the copy constructor "move" semantics for efficiency reasons.

The functions make_vector, make_list, and make_deque themselves just provide the convenience of automatic template parameter deduction. In this sense they are similar to the standard function make_pair.

Using Inline Containers

To use this code for implementing variable arguments, create a function that takes a reference to a vector (the most efficient representation for this purpose). You can then pass vectors as well as the result of make_vector to your function.

Many programmers dream of having a variable-arguments max function. No matter how many arguments you pass and of what type, it will always return the biggest one. Now, due to the overloads I have added, you can do the following:

int a, b, c, d, e;
//...
int M = std::min(
  make_vector(a)(b)(c)(d)(e));

The source code is shown in Listing 1. Please note that the result of min and max is undefined for empty containers. (This works for me, but you may want to change it.) o

Andrei Alexandrescu is an Associate in the Components Group of Micro Modeling Associates. He may 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.