I have a specific question that I can't really find an answer to in all the questions regarding template member functions. I want to write a function that gets me some data and return it as a vector of a specific type.
I have the following:
#include <vector>
class testClass
{
public:
template <typename T> std::vector<T> getData(int column);
};
template <typename T> std::vector<T> testClass::getData(int column){
std::vector<T> returnData;
return returnData;
}
and to call the function:
int main()
{
testClass t;
std::vector<int> data = t.getData(0);
return 0;
}
When compiling this I get the error:
../templateTest/main.cpp:9:31: error: no matching member function for call to 'getData'
std::vector<int> data = t.getData(0);
~~^~~~~~~
../templateTest/testclass.h:8:42: note: candidate template ignored: couldn't infer template argument 'T'
template <typename T> std::vector<T> getData(int column);
^
Ok, so it can't get the template argument from the template in the return type. To fix this I try to include the template argument in the call:
int main()
{
testClass t;
std::vector<int> data = t.getData<int>(0);
return 0;
}
This compiles but gives me a linker error:
Undefined symbols for architecture x86_64:
"std::__1::vector<int, std::__1::allocator<int> > testClass::getData<int>(int)", referenced from:
_main in main.o
One final try is to include the template argument also in the function definition:
class testClass
{
public:
template <typename T> std::vector<T> getData<T>(int column);
};
This however doesn't compile... :
../templateTest/testclass.h:8:42: error: member 'getData' declared as a template
template <typename T> std::vector<T> getData<T>(int column);
Is it possible what I try to do?
Thanks!!
----------EDIT---------
Putting the implementation in the header does work. If you however prefer to have your implementation in the .cpp. Add the the last line for each implementation that you plan on using.
#include "testclass.h"
template <typename T> std::vector<T> testClass::getData(int column){
std::vector<T> returnData;
return returnData;
}
template std::vector<int> testClass::getData(int column);