Boost logo

Boost :

From: Tony D (tony_in_da_uk_at_[hidden])
Date: 2005-10-31 05:12:51


Hi people,

A couple years ago I wrote a container indexed by
type, which I've come to consider a basic building
block for reusable code. Effectively, code can use
"type_maps" to handle an arbitrary structure, without
needing to know member identifiers, and gets the speed
benefit of compile-time access resolution.

A simple implementation follows:

namespace NS
{
    namespace Private
    {
        class no_type2 { };
        class no_type3 { };
        class no_type4 { };
        class no_type5 { };

        template <typename T>
        class type_map_base
        {
          public:
            void operator=(const T& t) { t_ = t; }
            operator const T&() const { return t_; }

          private:
            T t_;
        };

        template<> class type_map_base<no_type2> { };
        template<> class type_map_base<no_type3> { };
        template<> class type_map_base<no_type4> { };
        template<> class type_map_base<no_type5> { };
    }

    template <typename T1,
              typename T2 = Private::no_type2,
              typename T3 = Private::no_type3,
              typename T4 = Private::no_type4,
              typename T5 = Private::no_type5>
    class type_map : public
Private::type_map_base<T1>,
                     public
Private::type_map_base<T2>,
                     public
Private::type_map_base<T3>,
                     public
Private::type_map_base<T4>,
                     public Private::type_map_base<T5>
    {
      public:
        using Private::type_map_base<T1>::operator=;
        using Private::type_map_base<T2>::operator=;
        using Private::type_map_base<T3>::operator=;
        using Private::type_map_base<T4>::operator=;
        using Private::type_map_base<T5>::operator=;
    };
}

// sample usage...

#include <iostream>
#include <string>

using namespace std;

int main()
{
    NS::type_map<int, string> tmid;
    tmid = 3;
    tmid = "hello";
    string s = tmid;
    cout << (int)tmid << ' ' << (string)tmid << ' '
         << s << endl;
    cout << sizeof(tmid) << " vs " << sizeof(int)
         << '+' << sizeof(string) << endl;
}

I've found typemaps useful for writing things like a
logging system that allows arbitrary criterion for
cataloging errors. To store several data items of the
same type, simply wrap each instance in a distinct
class (possibly using the template w/ unique number
idiom).

Implementation note: the empty base class optimisation
makes it practical to have a single template, avoiding
typelists (mpl sequences), preprocessing etc..

Cheers,

Tony

                
___________________________________________________________
How much free photo storage do you get? Store your holiday
snaps for FREE with Yahoo! Photos http://uk.photos.yahoo.com


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