Derek
Derek

Reputation: 11915

Template class for non-inline member functions

I am trying to follow an example here:

http://www.justsoftwaresolutions.co.uk/threading/implementing-a-thread-safe-queue-using-condition-variables.html

But I dont want to inline my function definitions with my class definition.

Will I have to put

template<typename Data>
concurrent_queue<Data>::

in front of all my function defs and constructors?

Upvotes: 3

Views: 4926

Answers (3)

Sebastian Mach
Sebastian Mach

Reputation: 39089

Yes, there is no way around that syntax (except with token-producing symbol-destroying evil evil #define macros).

Personally, I either inline them in the class template declaration/definition, or for the sake of better self-documentation put the definitions into some "inl"-file, like so:

foo.h

#ifndef FOO_H
#define FOO_H

namespace bar {

    template <typename T>
    class Foo {
    public:
        Foo () ;
        virtual ~Foo();
    };

}

#include "foo.inl.h"
#endif // FOO_H

foo.inl.h

#ifndef FOO_INL_H
#define FOO_INL_H

namespace bar {

template <typename T>
inline Foo<T>::Foo () {
}

template <typename T>
inline Foo<T>::~Foo () {
}

}
#endif // FOO_INL_H

Note that I explicitly declare them inline then. This improves consistency of the style, and if you happen to specialize the template, you have to do it anyways:

template <>
inline Foo<int>::Foo() {
}

Without the inline, you suffer the same pain like when forgetting it on ordinary functions defined in header files (read: multiple definition errors).

Upvotes: 3

tp1
tp1

Reputation: 1207

The functions do not need to be inline, but it's better if they are inside the header file:

/* in .h file */
template<class T>
class A
{
public:
   void f();
}

/* this also in .h file */
template<class T>
void A<T>::f()
{
}

This is often necessary to split the class and the functions to separate parts, but both of them needs to be in the header file for templates to work.

Upvotes: 0

Puppy
Puppy

Reputation: 146910

Yes, you will, and the definitions will still need to be in the header file. This is why everyone uses inline definitions- because they basically have to be inline anyway.

Upvotes: 3

Related Questions