Archive for the ‘C++’ Category

Test results for Boost 1.37.0 and CodeGear compilers…

November 5, 2008

… may be found here!

I ran the tests both before and after applying Update 1 and the results are exactly the same.

Boost 1.37 is out

November 4, 2008

As you probably know Boost 1.37 was released yesterday. I expect it to be well received by CodeGear users, as it includes many specific patches for both C++Builder 2009 and C++Builder 2007. The good news are that many of these patches actually disable workarounds that are not needed any more and none is specific to the latest compiler version, so apparently there are no new regressions.

Among the involved libraries there are some of the fundamental ones, as Config, CallTraits, Exception, Iterator, MPL and TypeTraits. Asio, Foreach, Filesystem, Function, Functional and Serialization also received patches. Unfortunately there were quite a few patches that I didn’t manage to submit in time; these will have to wait for 1.38, I’m afraid.

I hope to be able to post test results for both CB2009 and CB2007 on the bcbboost site by tomorrow evening. Originally I didn’t plan to issue a new bcbboost release, but CodeGear released Update 1 for CB2009 too late for explicit support to be included in 1.37. In the next few days I’ll check what needs to be done.

C++ Builder 2009, Boost & bcbboost

September 22, 2008

The number of visits to this blog has increased in the last few days. I obviously don’t know for sure, but C++ Builder 2009 was recently released and one possible reason for the increased traffic is that people are looking for information on Boost support for the new compiler.

As you probably know CB 2009 includes a custom version of Boost 1.35 . This includes a very high number of specific changes which, combined with the standard compliance improvements in the compiler, increase dramatically the level of support compared with previous releases. I would consider this a very convenient solution for those that do not need the latest libraries.

I’m currently in the process of helping the CodeGear people merge their changes into the official Boost repository and I hope to finish in time for the next Boost release, 1.37 . Should I not make it I plan to check with CodeGear whether they have any objection on issuing their patches through bcbboost first.

I currently have no plans for a 1.36 backport, but if you direly need it, let me know.

Searching for a raskal

August 5, 2008

A while ago, while trying to find my way around the intricacies of .NET’s approach to application configuration, I stumbled upon this article. As I found the approach it described as well as the code it provides very convenient, I built around it my own configuration support classes.

Now I would like to publish my current C# toolbox as Open Source and I’d like to include stuff that’s directly derived from the article I just mentioned. Thus I’m trying to get in touch with raskal, who originally posted the article on the Nezdeboeuf blog on the RioterDeckers’ Headquarters site, to ask his or her permission.

Hopefully sooner or later someone who knows how to reach her or him will google for one of these names and chance upon this post…

insert_separator

June 25, 2008

I recently realized that there is a problem that has kept cropping up regularly in my code for the last few months: transform a sequence of words in a comma separated list. Not a big issue in itself, but I find it interesting for two reasons: first, it is almost impossible to specify a solution that matches the regularity and simplicity of the expected outcome; second, it’s a good test case for checking how well different languages support writing a generic solution.

I have to confess that I wouldn’t have given it much thought if this wasn’t a kind of problem that really irks my sense of aesthetics; what you want is something as simple as:

string1, string2, string3

A very plain sequence, without any exception or special case. Yet when you try to code it you can’t avoid making a special case of either the first or the last string, as in this Python function:

def insert_separator1(l):
    ret = l[0]
    for s in l[1:]:
        ret += ", "
        ret += s
    return ret

Otherwise you have to insert a conditional inside the loop, which conceptually you should only need to compute once, as in this alternative Python implementation:

def insert_separator2(l):
    ret = ""
    first = True
    for s in l:
        if first:
            first = False
        else:
            ret += ", "
        ret += s
    return ret

By the way, I’m well aware that Python’s standard library provides a ready-made solution:

print ", ".join([ "string1", "string2", "string3" ])

While Python is very convenient to expose programming concepts, the code where this little problem keeps coming up is actually written in C#. This language also has a library solution, which is very similar to Python’s:

using System;

class InsertSeparator1
{
    static void Main(string[] args)
    {
        string[] l = { "string1", "string2",
                "string3" };
        System.Console.Out.WriteLine(
                string.Join( ", ", l));
    }
}

These library solutions are undoubtedly convenient, but they are limited to the scenario where you want to concatenate your list elements into a single string. Sometimes, however, you would rather output your strings to a file, or you might want to interleave other kinds of things, rather than just strings.

Let’s see then how different languages support a generic solution. Thanks to generators and duck typing Python makes it very easy:

import sys

def insert_separator4(elements, sep):
    first = True
    for e in elements:
        if first:
            first = False
        else:
            yield sep
        yield e

if __name__ == "__main__":
    for e in insert_separator4([ "string1",
            "string2", "string3" ], ", "):
        sys.stdout.write(e)
    sys.stdout.write( '\n' )

Slightly less so C#, which is constrained by static typing and the subordination of generics to inheritance as a means of generalization:

class InsertSeparator2
{
    static IEnumerable<ValueType>
            InsertSeparator<ValueType>(
                    IEnumerable<ValueType> elements,
                    ValueType sep)
    {
        bool first = true;
        foreach (ValueType e in elements)
        {
            if (first)
                first = false;
            else
                yield return sep;
            yield return e;
        }
    }

    static void Main(string[] args)
    {
        string[] l = { "string1", "string2",
                "string3" };
        foreach ( string e in
                InsertSeparator<string>(l, ", " ) )
        {
            System.Console.Out.Write(e);
        }
        System.Console.Out.WriteLine();
    }
}

Note that you need to implement the IEnumerable<T> interface in order to exploit this function.

C++ is also statically typed, but thanks to a form of compile time duck typing supported by templates it doesn’t require an abstract base class:

#include <iterator>
#include <iostream>
#include <string>

template <typename InputIter, typename OutputIter, 
        typename ValueType>
void insert_separator(InputIter first, 
        InputIter last, 
        OutputIter out, 
        ValueType sep)
{
    bool initial = true;
    while ( first != last )
    {
        if ( initial )
            initial = false;
        else
            *out++ = sep;
        *out++ = *first++;
    }
}

int main()
{
    std::string l[] = { "string1", "string2",
            "string3" };
    insert_separator(l, l + 3, 
            std::ostream_iterator<std::string>(
                    std::cout), 
            ", ");
}

At first sight the C++ solution isn’t much better than the C# one. However generalization is not just a matter of language constructs; it is also a matter of conceptual framework. With little effort from our part the function above integrates perfectly with the standard library’s iterators and containers, as well as with any user defined ones, provided they adhere to the standard library constraints.

Finally, there is a solution to this problem which satisfies my quest for elegance, but it’s currently late at night and this post is already long enough as it is 😉

The Borland / CodeGear compilers and Boost 1.35.0

May 5, 2008

One of the many changes introduced with the new Boost release process is a drastic reduction in the number of officially supported compilers.  Although all versions of the Borland /  CodeGear compiler were left out, it should be noted that this only means that they have been excluded from the official release branch regression tests. This is not a good thing, as it makes it likely that regressions introduced late in the release process go unnoticed until after the release is issued.

On the other hand all the specific workarounds that I’m aware of are still present in the Boost source code and compilers from 5.6.4 onward work only slightly worse with Boost 1.35.0 than they did with the last few Boost releases.

To get a more precise idea of what works and what doesn’t you can take a look at the test results for the 5.6.4, 5.8.2 and 5.9.3 compilers. As you can see the 5.9.3 compiler does somewhat better than the other two, but there are things that stopped working for all three since the last Boost release.

However, now that gcc and VC++ are both rather close to standard compliance, Boost authors tend to rely more and more on advanced techniques that are only partly supported by the latest compiler, and not at all from earlier ones. This is likely to get worse – or better, depending on points of view – with each new Boost release. Let’s just hope that CodeGear manages to keep up.

Standard C++ and GUI frameworks

October 15, 2007

A very common complaint against C++ is the lack of a standard GUI library. While I agree that it would be great to have one portable, modern GUI library, I don’t think it will ever happen. Traditionally, in the Windows market, GUI frameworks are a strong selling point for tool suppliers, so everybody has their own. Under Unix not only are GUI libraries mostly C oriented, but the one that emerged at one point as the vendor backed standard, namely Motif, has since been obscured by more attractive open source alternatives.

Among the cross platform C++ specific solutions available today QT and WxWidgets are probably the most popular ones, but they don’t appear to be suitable for inclusion in the standard. QT is produced by one of the field players and uses some non standard syntax, handled by a precompiler. The fact that Trolltech, QT’s developer, is including in it just about everything and the kitchen sink is not likely to help, even assuming that Trolltech is interested in QT’s inclusion in the standard, which isn’t something I would take for granted. WxWidgets, being an open source project, appears to be in a better shape from a political point of view, but while effective it can hardly be considered a modern design.

Another factor that must be taken into account is the advent of the web browser as an alternative interface paradigm. While I’m not convinced that this is an all-round superior alternative to GUI’s, it is often a valid contender and a more “fashionable” one. This is one of the reasons why I don’t see a business case for a new commercial C++ GUI framework and I don’t expect an open source one to emerge, especially in the light of the non trivial effort that a similar endeavour would entail.

Yet another option that is mentioned every now and again is the development and adoption of a simple, bare bones library. I don’t think such an approach would be of much use. In my opinion C++ is still chosen to develop GUI based applications because it guarantees responsiveness and control over appearance and behaviour of the interface. Ease of development is important, but not enough to be traded against speed and access to detail. This makes also adopting a thin wrapper over an existing , portable framework not viable. The other reason being that requesting vendors to supply an external library in order to comply with the standard would be awkward. The fact that C++ is defined by a standardization committee rather than by the developers of a reference implementation limits the extent to which an approach such as Python‘s “batteries included” may be applied.

In my opinion, however, there is an alternative approach that might have better chances of succeeding: rather than aiming for a full fledged GUI library it might be more effective to concentrate on the interface between the GUI and the application logic and forsake everything that relates to the visual aspect of the interface. The resulting library would include a framework for event handling and callbacks, which might be based on the Boost/TR1 Signals and Function libraries; paradigms for input /output towards visual components, from toggle buttons, to text fields, to combo boxes; and possibly a validation framework.

I’m aware that such an approach would leave out a good deal of GUI programming, but a sound design would encourage a clean separation of GUI and program logic, and probably lead to more testable code. A similar library could be implemented as a set of add-ons for existing GUI frameworks, without requiring the implementation of a completely new one.

A new release of bcbboost

September 15, 2007

I just released a new version of bcbboost, 1.34.1-5.9.2-0.2 , which supports Boost 1.34.1 and bcc32 5.9.2, which is the new compiler that’s part of C++Builder 2007 Update 3 and RAD Studio 2007. It should also work with bcc32 5.9.1 and 5.9.0, as well as with Boost 1.34.0 . This release includes improved support for the Iostreams and Parameters libraries.

Spirit 1.8.5 and 1.6.4 released

September 2, 2007

Spirit is a C++ parser generator framework that uses techniques such as template meta-programming and expression templates to allow expressing one’s grammars in a syntax that’s as close to EBNF as C++’s own syntax allows. Spirit is part of Boost.

Spirit 1.8.5 is a standalone variant of the version that is included in Boost 1.34.1; it doesn’t provide new features, but contains all the fixes that were applied since Spirit 1.8.4 . You can download Spirit 1.8.5 here.

Spirit 1.6.4 is the latest in a series of releases that are based on an earlier implementation that is friendlier towards older, less standard compliant compilers. It was specifically tested and works reasonably well with all Borland/CodeGear compilers from BCB6 onward. This is a bug fix only release and is likely to be the final 1.6.x version. Spirit 1.6.4 is available here.

Both Spirit 1.8.5 and 1.6.4 are available in the following variants:

Library only (the spirit-1.x.y.zip / spirit-1.x.y.tar.gz files) – These contain only Spirit itself and require an existing Boost installation. Both were tested only with Boost 1.34.0 and 1.34.1, but should work with other reasonably recent releases.

Miniboost (the spirit-1.x.y-miniboost.zip / spirit-1.x.y-miniboost.tar.gz files) – These contain also the minimal subset of Boost that is needed to use Spirit. This is a new version of the Miniboost that is based on Boost 1.34.1 and has the same directory structure as Boost itself.

An unbounded Sieve of Eratosthenes

August 30, 2007

This small program is a simplified implementation of an approach described in an old post by Alex Martelli on it.comp.lang.c++. There he demonstrated a use of streams, which are a metaphor for possibly infinite sequences whose elements are retrieved one at a time.

For each prime number we store in a vector a pair consisting of the prime itself and a multiple, initialized to the prime number again. We compare each candidate with each multiple; if the multiple is smaller we increment it by the corresponding prime. Then if the candidate is equal to the multiple we discard it as it’s obviously a multiple of the current prime, otherwise we move on to the next prime; when there isn’t any prime left we have found another one and we append it to the vector.

Thus this program performs the same operations as the traditional algorithm, but through a form of diagonalization it removes the original’s need for an upper bound. Rather neat, isn’t it? Here’s the code:

#include <cmath>
#include <iostream>
#include <limits>
#include <ostream>
#include <utility>
#include <vector>

typedef long long number;
typedef std::pair<number, number> prime;
typedef std::vector<prime> prime_vector;

int main() {
    prime_vector primes;
    number candidate = 2;
    for ( ; ; ) {
        prime_vector::iterator i = primes.begin();
        for ( ; i != primes.end(); ++i ) {
            while ( candidate > i->second )
                i->second += i->first;
            if ( candidate == i->second )
                break;
        }
        if ( i == primes.end() ) {
            std::cout << candidate << 'n';
            primes.push_back(prime(candidate, candidate));
        }
        ++candidate;
    }
}

As you probably noticed I’m using long long to represent my primes, so there’s an obvious hard limit at std::numeric_limits<long long>::max() (yes, I’m aware that long long isn’t in the standard yet); by using an arbitrary precision integer implementation the only limit is in the underlying hardware.In case you’re wondering why I used std::vector for an ever growing data structure, read what Alex Stepanov and Bjarne Stroustrup have to say about it. I didn’t make any benchmark, but for such small elements that are only appended at the back std::vector is likely to perform better than any other container. What I did notice is that vector reallocations don’t appear to cause any perceptible slowdown in the output flow.