Question:

C++: undefined reference?

by  |  earlier

0 LIKES UnLike

i've got an "undefined reference" error while trying to compile these 3 files:

---- file1: bla.h ----

template <class T>

class bla {

T abs;

int n;

public:

bla(int num, T el);

int getn();

};

--file 2: bla.cpp---

#include "bla.h"

template <class T>

bla<T>::bla(int num, T el) {

n = num;

abs = el;

}

template <class T>

int bla<T>::getn() {

return n;

}

---file 3:main.cpp---

#include "bla.h"

#include <iostream>

using std::cout;

int main() {

bla<char> mybla(5, 'a');

cout<<mybla.getn();

return 1;

}

i get the next 2 errors:

[Linker error] undefined reference to `bla<char>::bla(int, char)'

[Linker error] undefined reference to `bla<char>::getn()'

Is including the header file not enough?

What can I do?

Thanks.

 Tags:

   Report

1 ANSWERS


  1. a template class all must be of type class T

    so in you method bla(int num, T el) should be bla(T num, T el)

    and then type cast T num to the proper type. if you want to have two different types then you&#039;ll need two template types

    bla ( T num, M el ) where T is your integer type and M is a char type

    ex:

    template &lt;class T, class M&gt;

    T GetMin (T a, M b) {

      return (a&lt;b?a:b);

    }

Question Stats

Latest activity: earlier.
This question has 1 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.
Unanswered Questions