Soybean
July 18th, 2007, 05:31 PM
I'm still a little fuzzy on some of the details of C++ templates. I managed to get something like the following example working, but I don't understand why it works one way and not the other.
Without the bolded "inline", the following "thingy.hpp" still compiles, but fails to link if it's #included from more than one .cpp file. Inlining the specialization fixes it. Does anyone know why? Is there a way to do the same thing without inlining the function?
The relevant part of the linker error is "multiple definition of `void thingy::set<std::basic_string..." if that helps at all.
#ifndef THINGY_H_
#define THINGY_H_
#include <string>
#include <sstream>
using namespace std;
class thingy
{
public:
template<typename T>
void set(const T & s);
private:
string value;
};
template<typename T>
void thingy::set(const T & s)
{
stringstream ss;
ss << s;
ss >> value;
}
template<>
inline void thingy::set<string>(const string & s)
{
value = s;
}
#endif
Without the bolded "inline", the following "thingy.hpp" still compiles, but fails to link if it's #included from more than one .cpp file. Inlining the specialization fixes it. Does anyone know why? Is there a way to do the same thing without inlining the function?
The relevant part of the linker error is "multiple definition of `void thingy::set<std::basic_string..." if that helps at all.
#ifndef THINGY_H_
#define THINGY_H_
#include <string>
#include <sstream>
using namespace std;
class thingy
{
public:
template<typename T>
void set(const T & s);
private:
string value;
};
template<typename T>
void thingy::set(const T & s)
{
stringstream ss;
ss << s;
ss >> value;
}
template<>
inline void thingy::set<string>(const string & s)
{
value = s;
}
#endif