Reputation: 1
What I am trying to do:
// in foo.hpp
class foo {
private:
int m_a;
long m_b;
public:
foo(); // default constructor (defined in foo.cpp)
template<class T>
int Func1(int a, int b) {
// Func1 definition
// uses member variables m_a, m_b
}
}
// in foo.cpp
#include "foo.hpp"
foo::foo() {
// Foo constructor
// Uses member variables m_a, m_b
}
I understand templates in C++ work as a pattern and are instantiated on demand. Therefore, for the compiler to understand whats happening, the template method definition needs to be in the header file (or else I need to use the other workarounds like using an implementation file (.tpp) and including it in foo.hpp) This also applies to a template class with non-template methods. The non-template methods need to be defined in the header file. My question is Foo is a regular class and has one template method and a regular constructor. Should the constructor be defined in the header file or can it be defined in a separate source file?
I ran into this issue at work. Moving the constructor definition to the header file seems to fix the issue. It would be helpful if someone could provide an explanation for this behavior.
Upvotes: 0
Views: 117
Reputation: 11220
Should the constructor be defined in the header file or can it be defined in a separate source file?
As long as the constructor and the class itself is not a template, you can define it wherever you would like.
One point I would like to clarify: A template
s definition simply needs to be visible at the point of instantiation. This does not actually mean that a template
must always be defined in a header; it can just as easily be defined in the source file, if its only uses are meant to be internalized within the source file (e.g. it's a private
function, only used internally).
Often this does mean that it should be in a header for cases where it's either a public
function template, or a class template -- but there are exceptions to this rule.
Upvotes: 1