I am relatively new to C++, so my question may have an easy answer; however, I cannot find out why my code is not working when I thought it should. Sample code is as follows.
//a.h
#ifndef A
#define A
template<class T>
class a{
public:
a();
private:
T str;
};
#include "a.cpp"
#endif
//a.cpp
//#ifdef A
#include "a.h"
using namespace std;
template<class T>
a<T>::a(){
str = 'a';
}
//#endif
//driver.cpp
#include"a.h"
#include <string>
using namespace std;
void main(){
a<string> object;
}
I have been reading information online about how to get away from errors when including template. One of it being what I am trying to achieve here: having the #include "a.cpp"
in a.h
. However, the samples that I have looked at still uses #include "a.h"
in a.cpp
, shown in the sample code. However, I am getting the function template has already been defined
error. I found that using the #ifdef A
and commenting out the #include "a.h"
in a.cpp will help me get rid of this redefining error. But I want to understand what is happening. Shouldn't the redefinition be already taken care of by the include guard in a.h
?