0

Is there a convenient way to reduce code redundancy such as in this case?:

//Queue.h
template <class T>
class Queue {
public:
 Queue();
 ~Queue();
}

//Queue.cpp
template <class T> Queue<T>::Queue() { ... }
template <class T> Queue<T>::~Queue() { ... }

other than, potentially,

//Queue.cpp
#define QUEUE template <class T> Queue<T>::
QUEUE Queue() { ... }
QUEUE ~Queue() { ... }

I know you can define the member functions inside the header file/class declaration, but I'd assume that should be avoided, if possible?

djohoe28
  • 35
  • 7
  • duplicate of [Is it possible to avoid repeating the class name in the implementation file?](https://stackoverflow.com/questions/10887211/is-it-possible-to-avoid-repeating-the-class-name-in-the-implementation-file) - shortcut is to research the C++ Standard proposals for `namespace class` – underscore_d Jan 10 '20 at 11:16
  • Note that for templates you cannot split the declaration and definition of methods into separate files anyway: [Why can templates only be implemented in the header file?](https://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file) – Yksisarvinen Jan 10 '20 at 11:18
  • @Yksisarvinen No, you absolutely *can*, if you know in advance which specialisations you need and deliberately instantiate them in the implementation source file, after defining the member functions therein. – underscore_d Jan 10 '20 at 11:29

2 Answers2

2

Short answer is no.

You could look ahead to "C++ modules" for C++ 20.

But since you are using a template: So as to avoid linker issues (and for many other reasons), the definitions of template functions typically get inlined in the .h file itself

template <class T>
class Queue {
public:
 Queue() {
    ...
 }
 ~Queue() {
     ...
 }
 void Append(const T& t) {
    ...
 }
};

And then you don't need a .cpp file much less a fully qualified function name.

selbie
  • 100,020
  • 15
  • 103
  • 173
1

No

I know you can define the member functions inside the header file/class declaration, but I'd assume that should be avoided, if possible?

You need to ensure the definitions of all the members are visible to everywhere that instantiates the template, which often means they are in the header.

Caleth
  • 52,200
  • 2
  • 44
  • 75
  • Oh, my mistake, I meant "define" as in "write the function's contents right where you declare it", not just declaring it... ``` class Queue { Queue() { /* do this and that */ } ``` Should this be avoided? – djohoe28 Jan 10 '20 at 11:17
  • @djohoe28 preferring one way or another is a style issue. If you have a team used to out of line definitions, it might be preferable to keep the long name `template Queue::` – Caleth Jan 10 '20 at 11:22
  • Out-of-line definitions also mean less indentation and easier refactoring to separate files (be that an implementation file containing explicit instantiations, or just splitting into multiple header files), etc. – underscore_d Jan 10 '20 at 11:30