Jean-Luc Nacif Coelho
Jean-Luc Nacif Coelho

Reputation: 1022

C++ how to make templated code cleaner

I'm working with highly templated code in C++ and the code is driving me crazy, since I constantly have to mess around with abominations like this:

std::pair<typename P<A, B>::const iterator, std::pair<long, typename P<A, B>::const_iterator> p;

(no C++11 for tuple)

and this:

template <A, B, C, D, E>
class MyClass {
  private:
    P <A, B> p;
    Q <C, D> q;
    // (does nothing with A, B, C, D but has to use the template because
    // this class uses other templated classes P<A, B> and Q<C, D>)
    // ...
};

Is there a way to make the code cleaner and more readable like using typedef or other tricks?

EDIT: Think of P and Q as std::maps that i don't know the type.

Here is ~how my code works

template<A, B, C, D>
class MapWrapper {
  private:
    std::map< map<A, B>::const_iterator, map<C, D>::const_iterator > _map;

  public:
    void insert_in_map (map<A, B>::const_iterator one, map<C, D>::const_iterator two) {
        _map[one] = two;
    }
};

Upvotes: 1

Views: 144

Answers (1)

Yakov Galka
Yakov Galka

Reputation: 72479

One option is to rewrite it to

template <class P, class Q>
class MyClass {
  private:
    P p;
    Q q;
};

and instead uses like

MyClass<A, B, C, D, E>

change them to

MyClass<P<A, B>, Q<C, D>>

This, with correct use of typedefs, may reduce the amount of boilerplate.

Another option is to pay with runtime performance by applying some type erasure (i.e. use less templates).

EDIT: following your edit, in your concrete code, you can generalize your class to work with any pairs of iterators:

template<class I1, class I2>
class MapWrapper {
  private:
    std::map<I1, I2> _map;

  public:
    void insert_in_map (I1 one, I2 two) {
        _map[one] = two;
    }
};

Depending on the algorithmic part, this may, or may not, make sense.

Upvotes: 2

Related Questions