0
#include "ArrayList.h"

template <typename T>
ArrayList<T>::ArrayList(): innerArray(new T[0]), len(0) {
    // constructor stuff
}
template <typename T>
ArrayList<T>::~ArrayList() {
    // destructor stuff
}
... on and on and on ...

In this code, I have to write template <typename T> and ArrayList<T>:: before every member function in the entire class.

Is there any way to eliminate this repetition (DRY), so I can do something like

#include "ArrayList.h"
// do some magic

ArrayList(): innerArray(new T[0]), len(0) {
    // constructor stuff
}
~ArrayList() {
    // destructor stuff
}
tckmn
  • 57,719
  • 27
  • 114
  • 156
  • 7
    You know you need to keep the implementation in the header anyway, right? So why not define them inside the class? – Luchian Grigore Jun 10 '13 at 01:34
  • I don't think that's considered repeating yourself... – David G Jun 10 '13 at 01:34
  • @LuchianGrigore Wait, doesn't the implementation go in the `.cpp` and the definition in the header? – tckmn Jun 10 '13 at 01:35
  • @0x499602D2 I'd say an identical line before every single method in my class would be repeating myself... – tckmn Jun 10 '13 at 01:35
  • For templates, the implementation has to be visible to TU's that use it. – Luchian Grigore Jun 10 '13 at 01:36
  • 1
    http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file – Luchian Grigore Jun 10 '13 at 01:36
  • 2
    Also, `innerArray(new T[0])` is not right. Do `innerArray(nullptr)` instead. – David G Jun 10 '13 at 01:37
  • @Doorknob In the case of non-template classes, sure; you can separate the implementation from the interface. Not so with templates. You MUST have the implementation available when the template is instantiated by the compiler. So you should just define them inline since they need to be in the header anyway. – KitsuneYMG Jun 10 '13 at 20:20

1 Answers1

0

I suppose you can use a macro:

#define DEFINE_ARRAYLIST_TEMPLATE(F, ...) template <typename T> \
                                          A<T>::F(__VA_ARGS__)

Use it to do this:

DEFINE_ARRAYLIST_TEMPLATE(ArrayList) : innerArray(nullptr), len(0)
//                                                ^^^^^^^ < my earlier suggestion
{}

DEFINE_ARRAYLIST_TEMPLATE(ArrayList, int n) : innerArray(new T[n]), len(n)
{}

DEFINE_ARRAYLIST_TEMPLATE(~ARRAYLIST)
{}
David G
  • 94,763
  • 41
  • 167
  • 253