Hi
I have been developing a library which has the following structure (simplified for the purposes of the explanation):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
|
// myLibrary.h
#include "HelperClass.h"
class myLibrary {
private:
struct Details {
string nm;
int age;
} details;
HelperClass some_data;
public:
int getNum();
HelperClass getData();
};
//myLibrary.cpp
int myLibrary::getNum() {
return num;
}
HelperClass myLibrary::getData() {
return some_data;
}
//main.cpp
myLibrary mLib;
|
myLibrary and HelperClass are compiled to form a static library ("myLibrary.a" file) which the client can link to when using myLibrary.
I'd like to make myLibrary a templated class so that the client using the library can supply a type T for the details member i.e.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
// myLibrary.h
class myLibrary {
private:
T details;
...
};
// main.cpp
struct custom_details{
string nm;
bool isSomething;
};
myLibrary <custom_details> mLib;
|
However, I understand that, for templated classes, the interface (header file) cannot be separated from the implementation file (cpp file). So my options are either to:
1.) Make explicit the instantiations of T - this doesn't work as the client could supply any type for T.
2.) Put the method definitions of myLibrary<T> in myLibrary.h. Either:
(a) Directly in myLibrary.h; or
(b) Creating an intermediate file (a ".tpp" file) with the definitions and including this intermediate file at the end of myLibrary.h.
Option 2(b) is more convenient for me as I will not have to move all of the method definitions from myLibrary.cpp to myLibrary.h and I can rename myLibrary.cpp to myLibrary.tpp (and add template definitions to each method). It also helps keep the appearance of a interface/implementation distinction which aids readability.
For 2(b), I think myLibrary becomes a header only library and so the client would simply include myLibrary.h rather than linking to myLibrary.a.
Given the above, I had a couple of
questions:
(A) Is the understanding set out above correct? Have I missed any easier solutions? I'd considered using something like std::any for details but I understand that using std::any is discouraged.
(B) Will HelperClass, which will not be a templated class, need to be header only as well or would the client still link to something like HelperClass.a?
Thanks very much