Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid repeating class name and template call in implementation?

I find the code below terribly difficult to read, and I wrote it! Is there any to

  1. avoid calling template for each implemented member function
  2. avoid having ClassName::member_function_name for each implemented member function? I find Java DRYer in this regard. You don't repeat the class name everywhere.

Thanks!

template <class KeyType, class ObjectType>
class Vertex
{
private:
    KeyType key;
    const ObjectType* object;
public:
    Vertex(const KeyType& key, const ObjectType& object);
    const KeyType getKey();
};

template <class KeyType, class ObjectType> 
class Graph
{
private:
    map<KeyType, Vertex<KeyType, ObjectType> > vertexes;
public:
    const Vertex<KeyType, ObjectType>& createVertex(const KeyType& key, const ObjectType& object);
};

template <class KeyType, class ObjectType>
Vertex<KeyType, ObjectType>::Vertex(const KeyType& objectKey, const ObjectType& newObject)
{
    key = objectKey;
    object = &newObject;
};

template <class KeyType, class ObjectType>
const KeyType Vertex<KeyType, ObjectType>::getKey()
{
    return key;
};

template <class KeyType, class ObjectType>
const Vertex<KeyType, ObjectType>& Graph<KeyType, ObjectType>::createVertex(const KeyType& key, const ObjectType& object)
{
    Vertex<KeyType, ObjectType> *vertex = new Vertex<KeyType, ObjectType>(key, object);
    vertexes.insert(make_pair(vertex->getKey(), *vertex));
    return *vertex;
};
like image 338
Alexandre Avatar asked Oct 25 '22 15:10

Alexandre


1 Answers

I think that in this case, you can easily define the functions in the declaration, and use some typedefs to clear the syntax.

template <class KeyType, class ObjectType>
class Vertex {
  public:
    Vertex(const KeyType& key, const ObjectType& object) :
           key(objectKey), object(&newObject) { };
    const KeyType getKey() const { return key; };
  private:
    KeyType key;
    const ObjectType* object;
};

template <class KeyType, class ObjectType> 
class Graph {
  public:
    typedef Vertex<KeyType, ObjectType> vertex_type;

    const vertex_type& createVertex(const KeyType& key, const ObjectType& object) {
      vertex_type* vertex = new vertex_type(key, object);
      vertexes.insert(make_pair(vertex->getKey(), *vertex));
      return *vertex;
    };
  private:
    map<KeyType, vertex_type > vertexes;
};
like image 112
Mikael Persson Avatar answered Oct 27 '22 11:10

Mikael Persson