7
   I'm getting an "unresolved external symbol "public:__thiscall hijo<int>::hijo<int>(void)" referenced in function_main

I started a new project cause I was having this same error on another larger project. The error occur when I try to allocate space using the new keyword. If this error is silly please forgive me cause I haven't programmed anything in the last months.

  /********************file hijo.h******************/
#pragma once
#ifndef hijo_h
#define hijo_h

template <class A>
class hijo
{
public:
    hijo(void);
    ~hijo(void);
};
#endif


  /********************file hijo.cpp***************/
    #include "hijo.h"
#include <iostream>
using namespace std;

template <class A>
hijo<A>::hijo(void)
{
}
template <class A>
hijo<A>::~hijo(void)
{
}
  /*********************at main() function ***************/

#include <iostream>
#include "hijo.h"

int main(){

    hijo<int> *h = new hijo<int>; <----  PROBLEM AT THIS LINE

    system("pause");
    return 0;
}
templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
HoNgOuRu
  • 717
  • 4
  • 13
  • 26

1 Answers1

12

Due to a weirdness in C++'s compilation model, you cannot separate out .h and .cpp files very cleanly for template classes. Specifically, any translation unit (C++ source file) that wants to use a template class has to have access to the entire template definition. This is a strange quirk of the language, but unfortunately it's here to stay.

One option is to put the implementation up in the header file rather than in the source, then to not have a .cpp file at all. For example, you might have this header:

#pragma once
#ifndef hijo_h
#define hijo_h

template <class A>
class hijo
{
public:
    hijo(void);
    ~hijo(void);
};

/* * * * Implementation Below This Point * * * */

template <class A>
hijo<A>::hijo(void)
{
}
template <class A>
hijo<A>::~hijo(void)
{
}

#endif

Hope this helps!

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
  • "but unfortunately it's here to stay" -- until we get modules. \*crosses fingers* – Xeo Feb 07 '12 at 05:43
  • WORKS LIKE A CHARM, just had to do a little fix to your solution. instead of adding the code in the .h file i just included the .cpp file at the bottom of the .h file. It's same result as if both parts were in the same file. in "hijo.cpp" #ifndef hijo_cpp #define hijo_cpp and at the bottom #endif... thank u for your answer... – HoNgOuRu Feb 07 '12 at 05:44
  • gotta wait 8 more minutes to mark the question as answered – HoNgOuRu Feb 07 '12 at 05:45
  • Adding an Explicit specialization for the exact types at he end of the cpp file which defines the template functions will work too.However the use of this technique should be limited to small modules/projects. – Alok Save Feb 07 '12 at 05:48