templates

Working with traits…

URGH!

I’m trying to write something along the lines of:


template<typename _ItrType>
static size_t countThings(_ItrType begin, _ItrType end)
{
  size_t numThings = 0 ;
  for ( _ItrType it = begin ; it != end ; ++it )
  {
    Entity& entity = getEntityFromIterator(it) ;
    numThings += entity.numThings ;
  }
}

// Handle associative iterators.
template<typename _KeyType>
Entity& getEntityFromIterator(std::pair<_KeyType, Entity&>& it)
{
  return it.second ;
}

template<typename _KeyType>
Entity& getEntityFromIterator(std::pair<_KeyType, Entity*>& it)
{
  return *(it.second) ;
}

template<typename _KeyType>
Entity& getEntityFromIterator(std::pair<_KeyType, Entity>& it)
{
  return it.second ;
}

// Handle sequence iterators.
template<typename _ItrType>
Entity& getEntityFromIterator(_ItrType& it)
{
  return *it ;
}

I.e. something that will allow me to write a function that will take an iterator range and worry about whether the iterators are sequence or container for me at compile time.

But it always falls thru to my last case. The error from GCC indicates that I need to specifically look ¬†std::_RB_tree_iterator<std::pair<_KeyType, Entity>> etc, but I’d rather not. I’m wanting to do something to peel back until we get to an Entity, e.g.

template<typename _Outer, typename _Inner>get(_Outer<_Inner>& container) { return *container ; }
template<typename _Key, typename _Value> get(_Key, _Value entity) { return get(entity) ; }
get(Entity& entity) { return entity ; }
get(Entity* entity) { Return *entity ; }

Cannot seem to find a way to get this to work, and I’m starting to think I probably need to do some traits jiggery-pokery. Grr.

C++ Templates, avoiding virtual

I’ve not done a great deal with C++ Templates, and especially with some of the improvements in C++0x, I’m thinking I’d like to change that.

One particular example I’m tinkering with right now is a database abstraction layer I’ve been dragging around with me for years. It has two primary members: DBQuery and DBRow. Up until now they have been littered with #ifdef’s. I want to ditch the ifs and switch to templates.