Wednesday, March 28, 2018

c++ - Undefined reference error for template method





This has been driving me mad for the past hour and a half. I know it's a small thing but cannot find what's wrong (the fact that it's a rainy Friday afternoon, of course, does not help).



I have defined the following class that will hold configuration parameters read from a file and will let me access them from my program:



class VAConfig {
friend std::ostream& operator<<( std::ostream& lhs, const VAConfig& rhs);

private:
VAConfig();
static std::string configFilename;

static VAConfig* pConfigInstance;
static TiXmlDocument* pXmlDoc;
std::map valueHash;

public:
static VAConfig* getInstance();
static void setConfigFileName( std::string& filename ) { configFilename = filename; }
virtual ~VAConfig();

void readParameterSet( std::string parameterGroupName );

template T readParameter( const std::string parameterName );
template T convert( const std::string& value );
};


where the method convert() is defined in VAConfig.cpp as



template 
T VAConfig::convert( const std::string& value )
{

T t;
std::istringstream iss( value, std::istringstream::in );
iss >> t;
return t;
}


All quite simple. But when I test from my main program using



int y = parameters->convert("5");



I get an undefined reference to 'int VAConfig::convert...' compilation error. Ditto for readParameter().



Looked at a lot of template tutorials but coul not figure this out. Any ideas?


Answer



Templated code implementation should never be in a .cpp file: your compiler has to see them at the same time as it sees the code that calls them (unless you use explicit instantiation to generate the templated object code, but even then .cpp is the wrong file type to use).



What you need to do is move the implementation to either the header file, or to a file such as VAConfig.t.hpp, and then #include "VAConfig.t.hpp" whenever you use any templated member functions.


No comments:

Post a Comment

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...