duplicate definitions with template member function

M

mathieu

Why is the following code causing duplicate definitions (gcc 4.2) when
including swapper.h in multiple files ?

Thanks
-Mathieu

--------swapper.h-----------
#ifndef swapper_h
#define swapper_h

class Swapper
{
public:
template <typename T> static T Swap(T val);
template <typename T>
static void SwapArray(T *array, unsigned int n)
{
for(unsigned int i = 0; i < n; ++i)
{
array = Swap<T>(array);
}
}
};
#include "swapper.txx"
#endif

--------swapper.txx-----------
#ifndef swapper_txx
#define swapper_txx

template <> uint16_t Swapper::Swap<uint16_t>(uint16_t val)
{
return bswap_16(val);
}
template <> uint32_t Swapper::Swap<uint32_t>(uint32_t val)
{
return bswap_32(val);
}
template <> uint64_t Swapper::Swap<uint64_t>(uint64_t val)
{
return bswap_64(val);
}

#endif
 
V

Victor Bazarov

mathieu said:
Why is the following code causing duplicate definitions (gcc 4.2) when
including swapper.h in multiple files ?

Because 'spapper.txx' contains definitions (explicit specialisations).
Those aren't templates, and as such need to be placed in a translation
unit instead of a header which is included in more than one TU.
Thanks
-Mathieu

--------swapper.h-----------
#ifndef swapper_h
#define swapper_h

class Swapper
{
public:
template <typename T> static T Swap(T val);
template <typename T>
static void SwapArray(T *array, unsigned int n)
{
for(unsigned int i = 0; i < n; ++i)
{
array = Swap<T>(array);
}
}
};
#include "swapper.txx"
#endif

--------swapper.txx-----------
#ifndef swapper_txx
#define swapper_txx

template <> uint16_t Swapper::Swap<uint16_t>(uint16_t val)
{
return bswap_16(val);
}
template <> uint32_t Swapper::Swap<uint32_t>(uint32_t val)
{
return bswap_32(val);
}
template <> uint64_t Swapper::Swap<uint64_t>(uint64_t val)
{
return bswap_64(val);
}

#endif


V
 
M

mathieu

Because 'spapper.txx' contains definitions (explicit specialisations).
Those aren't templates, and as such need to be placed in a translation
unit instead of a header which is included in more than one TU.

Ah of course ! Thanks Victor.

Well the issue here is that I am trying to avoid a function call,
since the bswap* will get called in a for loop.

Thanks again,
-Mathieu
 
V

Victor Bazarov

mathieu said:
Ah of course ! Thanks Victor.

Well the issue here is that I am trying to avoid a function call,
since the bswap* will get called in a for loop.

Try declaring those specialisations "inline".

V
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top