Как избежать повторения имени класса и вызова шаблона в реализации? - PullRequest
5 голосов
/ 05 апреля 2011

Я нахожу код ниже ужасно трудным для чтения, и я написал его!Можно ли

  1. избегать вызова шаблона для каждой реализованной функции-члена
  2. избегать использования ClassName::member_function_name для каждой реализованной функции-члена?Я нахожу Java DRYer в этом отношении.Вы не повторяете имя класса везде.

Спасибо!

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;
};

Ответы [ 3 ]

1 голос
/ 05 апреля 2011

Это должно быть «почти» эквивалентно вашему коду. «почти», потому что, как сказал xDD, внутреннее определение функции-члена неявно помечает их как встроенные.

Класс по умолчанию закрытый, а Struct общедоступный по умолчанию.

template <class KeyType, class ObjectType>
class Vertex
{
    KeyType key;
    const ObjectType* object;

    public:
        Vertex(const KeyType& _key, const ObjectType& _object) : key(_key), object(&_object) {}

        const KeyType getKey()
        {
            return key;
        }
};

template <class KeyType, class ObjectType> 
class Graph
{
    map<KeyType, Vertex<KeyType, ObjectType> > vertexes;

    public:
        const Vertex<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;
        }
};

или с typedef:

template <class KeyType, class ObjectType>
class Vertex
{
    KeyType key;
    const ObjectType* object;

    public:
        Vertex(const KeyType& _key, const ObjectType& _object) : key(_key), object(&_object) {}
        const KeyType getKey()
        {
            return key;
        }
};

template <class KeyType, class ObjectType> 
class Graph
{
    typedef Vertex<KeyType, ObjectType> tVertex;
    map<KeyType, tVertex > vertexes;

    public:
        const tVertex& createVertex(const KeyType& key, const ObjectType& object)
        {
            tVertex *vertex = new tVertex(key, object);
            vertexes.insert(make_pair(vertex->getKey(), *vertex));
            return *vertex;
        }
};
1 голос
/ 05 апреля 2011

Я думаю, что в этом случае вы можете легко определить функции в объявлении и использовать некоторые typedef для очистки синтаксиса.

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;
};
1 голос
/ 05 апреля 2011

Поскольку это шаблон, почему бы не определить функции-члены прямо в теле класса?

Код должен быть доступен в модуле компиляции в любом случае, поэтому вы не получите никакого ускорения времени компиляции, если отделите объявление от определения, и компиляторы в настоящее время достаточно умны, чтобы самостоятельно определять необходимость встраивания.

...