Boost logo

Boost :

From: Terje Slettebø (tslettebo_at_[hidden])
Date: 2003-03-27 23:35:10


>From: "Jason House" <jhouse_at_[hidden]>

> I had 2 thoughts today...
>
> 1. Is it at all useful/possible to use a lambda-like notation?

In what way? Could you have given a rough syntax-example?

An example in BLL is:

std::for_each(v.begin(), v.end(), std::cout << _1 << '\n');

> In the past, I've liked the look of that a lot.
> (the comments about alternate notation made me think of it)
>
> 2. Why are we restricting the output to strings?

That _is_ a natural question, isn't it? :)

> Couldn't the types of the 3 delimiter strings actually be
> implicit template parameters?
> (the char/wchar versions made me think of that)

Yes, that is how it currently works; it deduces the types passed to the
format function template, and returns an object of type format_type
(analogous to many cases, such as bind1st/binder1st).

Since all the string parameters have default to empty string, this is done
by having three overloads of the format function template - for
std::basic_string, const char * and const wchar_t *. That way, you can use
"", L"", etc. as appropriate, for the default.

As mentioned in some previous postings, a possibility for generalising the
formatting could be to pass a "visitor" object to the format-function,
instead of the strings, which is then invoked at the specific times during
output (begin/end sequence, etc.). One could then also support things like
line numbers and indentation, without hardcoding how this is done. It would
also be possible to make a visitor object which took strings in the
constructor, and gave the current semantics.

This approach seems to require dynamical allocation of the format data, and
virtual functions, though. Since this means quite a bit of change, I haven't
done it so far, but I'm open to the possibility.

An example of its use:

// Line numbering visitor (could be included in the library)
//
// All virtual functions are included for illustration. In practice, the
once with empty body could be omitted.

template<class T, class CharType, class CharTraits>
class numbering_type : public visitor_base
{
public:
  explicit numbering(int ln) : line_number(ln) {}

  virtual void start_sequence(std::basic_ostream<CharType,CharTraits>
&stream) {}
  virtual void end_sequence(std::basic_ostream<CharType,CharTraits> &stream)
{}
  virtual void element(std::basic_ostream<CharType,CharTraits> &stream,
const T &element)
    { stream << line_number << ' ' << element << '\n'; ++line_number; }

private:
  int line_number;
};

// The numbering function template returns a numbering_type object

typedef std::vector<char> vector;

vector v;

// Fill vector

std::cout << format<vector>(numbering())
          << v;

Output:

1 - A
2 - B
3 - C

etc.

Thanks.

Regards,

Terje


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk