duplicate definitions with template member function

Discussion in 'C++' started by mathieu, Dec 18, 2007.

  1. mathieu

    mathieu Guest

    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
     
    mathieu, Dec 18, 2007
    #1
    1. Advertisements

  2. 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.


    V
     
    Victor Bazarov, Dec 18, 2007
    #2
    1. Advertisements

  3. mathieu

    mathieu Guest

    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
     
    mathieu, Dec 18, 2007
    #3
  4. Try declaring those specialisations "inline".

    V
     
    Victor Bazarov, Dec 18, 2007
    #4
  5. mathieu

    mathieu Guest

    Cool ! This is at least working for my compiler :)

    Thanks
    -Mathieu
     
    mathieu, Dec 18, 2007
    #5
    1. Advertisements

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 (here). After that, you can post your question and our members will help you out.