I have the following template method:
struct MyStruct
{
// ...
template<typename T>
void readField(std::istream& in, T& data)
{
read(in, data);
data = ntohl(data);
}
};
template<>
void MyStruct::readField<uint8_t>(std::istream& in, uint8_t& data)
{
read(in, data);
}
But I get those strange linker errors:
/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/exception:62: multiple definition of `void MyStruct::readField(std::basic_istream >&, unsigned char&)' ../Lib/obj/MyStruct.o:/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/exception:62: first defined here collect2: ld returned 1 exit status make: *** [Lib] Error 1
How can I specialize this member function?
EDIT
This approach works:
struct MyStruct
{
// ...
template<typename T>
void readField(std::istream& in, T& data)
{
read(in, data);
data = ntohl(data);
}
void readField(std::istream& in, uint8_t& data)
{
read(in, data);
}
};
or with inline
s or specializing it outside the class with inline
struct MyStruct
{
// ...
template<typename T>
void readField(std::istream& in, T& data)
{
read(in, data);
data = ntohl(data);
}
};
template<>
inline void MyStruct::readField<uint8_t>(std::istream& in, uint8_t& data)
{
read(in, data);
}
inline
. – Igor Tandetnikinline
. Why is that so? – PatrykI can define this method in the header file without inline
Clearly you cannot, or you woudln't be here asking questions. You get a linker error when you try, don't you? Perhaps I misunderstand what you are trying to say. – Igor Tandetnikinline
. What I can do is as you mentioned specialize it withinline
but only outside the class definition. Thanks a lot – Patrykinline
. – Igor Tandetnik