I am aware of the technicality that arises when someone uses templates in C++ classes/structs but still wants to follow the accepted (quite established) approach of splitting declarations into header(.hpp) files from definitions into source(.cpp) files.
I have done a mini-research in different blogs/forums, searching for a safe and systematic way to adopt and split the declarations from the definitions.
From this, (see answer 1) I am almost convinced that it is not a trustworthy approach to write a template class library and distribute it with header and lib files to hide the implementation. So, only the safe way to go is to directly write the definitions and the declarations in the same file (.hpp).
However, in another blog here I saw a workaround approach, that suggests doing a kind of circular dependency between the source and header files. By "circular dependency" I mean to include at the bottom of the header file the source code #include "Input.cpp"
, and as usual, in the source code include the header file #include "Input.hpp"
on the top.
This is the example header file:
#ifndef INPUT_H_
#define INPUT_H_
template <class T>
class Input
{
public: // Constructors:
Input(T whatever);
};
#include "Input.cpp"
#endif
and this is the example source code:
#ifndef INPUT_CPP_
#define INPUT_CPP_
#include "Input.h"
template <class T>
Input<T>::Input(T whatever)
{
/* some code here */
}
#endif
According to the answers that I found, the only issue in the circular dependency approach is the double-definition issue, which was resolved by adding preprocessor definitions in both files!
Now, my question is: Is it indeed a good practice to adopt, or maybe because of its simplicity (we used a very simple test case) it fails to prove that it is actually a bad approach?
Can someone provide evidence to show if this circular-dependency approach has any limitations?
Aucun commentaire:
Enregistrer un commentaire