template specialization according to sizeof type

前端 未结 4 1714
南旧
南旧 2021-02-05 09:29

I would like to provide a templated function, that varies its implementation (->specialization) according to the sizeof the template type.

Something similar to this (omi

4条回答
  •  南方客
    南方客 (楼主)
    2021-02-05 09:42

    I can propose the following method: Its benefit is that you don't have to throw an exception if the operand isn't of the valid size. It just won't link. So that you have the error checking at build time.

    template
    void byteswapInPlace(void* p);
    
    template<> void byteswapInPlace<1>(void* p) { /* do nothing */ }
    
    template<> void byteswapInPlace<2>(void* p)
    {
        _byteswap_ushort((ushort*) p);
    }
    
    template<> void byteswapInPlace<4>(void* p)
    {
        _byteswap_ulong((ulong*) p);
    }
    
    template<> void byteswapInPlace<8>(void* p)
    {
        _byteswap_uint64((uint64*) p);
    }
    
    
    template
    T byteswap(T & swapIt)
    {
        byteswapInPlace(&swapIt);
        return swapIt;
    }
    

提交回复
热议问题