0

I have a class called SomeClass with a template

someclass.hpp

template<typename T>
SomeClass 
{    
public:    
   SomeClass(T& it, int a): t(it), b(a) {
      CallMethod();    
}

static void PrintSomething() {
    std::cout << "static method in SomeClass" <<std::endl;
}

private:
T& t;
int b;
void CallMethod();
}

Methods are defined in someclass.cpp

void SomeClass<T>::Callmethod() {
   t.SomeMethod();
}

Now, in main.cpp, I have,

T t;
t.SomeMethod(); //no error
SomeClass<T>::PrintSomething(); //call only this static method, it works

SomeClass<T> SomeClass(t, 2); //error

Errors are Undefined reference to all methods called inside the constructor. And undefined reference to destructor. This Only when I instantiate an object. No problems I call a static method from the class. I have included the object file in Make.

My makefile.

OBJECTS = \
    src/main.o \
    Src/someclass.o \

sys: $(OBJECTS)
    $(CXX) $(CXXFLAGS) -o sys $(OBJECTS) $(LIB)

Any obvious errors? Help appreciated.

user592748
  • 1,194
  • 3
  • 21
  • 45
  • 1
    Template definitions have to be in the same file as the declarations. – chris Mar 15 '13 at 11:05
  • 3
    @chris unless they are instantiated in the `cpp` for every type needed. – Peter Wood Mar 15 '13 at 11:06
  • @PeterWood, That kind of defeats the purpose of using a template :p I guess it could save on code for a class, but functions you could just overload. – chris Mar 15 '13 at 11:07
  • @PeterWood can you explain how and where I instantiate in the .cpp file the type I need? – user592748 Mar 15 '13 at 11:23
  • @chris According to the link, I need to include the implementation file at the end of the header file. But can this result in multiple definition error if 2 of the classes include this header file and then main includes both of these classes? – user592748 Mar 15 '13 at 11:23
  • @user592748 No, templates won't cause a multiple definition error. – Peter Wood Mar 15 '13 at 11:24
  • @chris There are lots of ways to use, and reasons for using, templates. – Peter Wood Mar 15 '13 at 11:25
  • 1
    @user592748 You're probably best off putting them in the header. It is likely the correct thing to do. I'm just rounding out chris' simplification of the facts. – Peter Wood Mar 15 '13 at 11:28
  • @PeterWood, Well, I appreciate it. I haven't actually thought much more about this beyond including the implementation in the header. – chris Mar 15 '13 at 11:33

0 Answers0