S
szczeles
Hello everyone,
I'm trying to write some code in c++ using templates. When I place
simple template-based function in one file, for example:
//----main.cpp-----
#include <iostream>
using namespace std;
template <class T>
T add(T a, T b) {
return a + b;
}
int main() {
cout << 1.5f << " + " << -0.4f << " = " << add(1.5f, -0.4f) << endl;
cout << 4 << " + " << 10 << " = " << add(4, 10) << endl;
}
//-----------------
everything works good, but if funcion add() is in another file, for
example in functions.cpp and its definition is in header file which I
include in main.cpp I can compile functions.cpp only, but `g++
main.cpp functions.cpp` results in error:
mario@laptok:~/cpptest$ g++ main.cpp functions.cpp
/tmp/ccW3MdFX.o: In function `main':
main.cpp.text+0x96): undefined reference to `float add<float>(float,
float)'
main.cpp.text+0x114): undefined reference to `int add<int>(int,
int)'
Is there any possibility to place template-based function in other
file?
Any help will be appreciated.
szczeles
I'm trying to write some code in c++ using templates. When I place
simple template-based function in one file, for example:
//----main.cpp-----
#include <iostream>
using namespace std;
template <class T>
T add(T a, T b) {
return a + b;
}
int main() {
cout << 1.5f << " + " << -0.4f << " = " << add(1.5f, -0.4f) << endl;
cout << 4 << " + " << 10 << " = " << add(4, 10) << endl;
}
//-----------------
everything works good, but if funcion add() is in another file, for
example in functions.cpp and its definition is in header file which I
include in main.cpp I can compile functions.cpp only, but `g++
main.cpp functions.cpp` results in error:
mario@laptok:~/cpptest$ g++ main.cpp functions.cpp
/tmp/ccW3MdFX.o: In function `main':
main.cpp.text+0x96): undefined reference to `float add<float>(float,
float)'
main.cpp.text+0x114): undefined reference to `int add<int>(int,
int)'
Is there any possibility to place template-based function in other
file?
Any help will be appreciated.
szczeles