template specialization according to sizeof type

前端 未结 4 1712
南旧
南旧 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:51

    You don't need SFINAE or type traits. Vanilla template specialization is enough. Of course it must be specialized on structs as C++(98) doesn't support function template partial specialization.

    template 
    struct ByteswapImpl
    /*
    {
      T operator()(T& swapIt) const { throw std::exception(); }
    }
    */    // remove the comments if you need run-time error instead of compile-time error.
    ;
    
    template 
    struct ByteswapImpl {
      T operator()(T& swapIt) const { return _byteswap_ushort (swapIt); }
    };
    
    // ...
    
    template 
    T byteswap(T& swapIt) { return ByteswapImpl()(swapIt); }
    

提交回复
热议问题