template specialization according to sizeof type

前端 未结 4 1784
南旧
南旧 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条回答
  •  旧时难觅i
    2021-02-05 09:57

    Simply make an auxiliary class that takes the size as a template argument:

    #include 
    #include 
    
    
    template
    struct ByteSwapper { };
    
    template<>
    struct ByteSwapper<2> {
      static unsigned short swap(unsigned short a) {
        return 2 * a;
      }
    };
    
    template
    T byteswap(const T& a) {
      return ByteSwapper::swap(a);
    }
    
    
    int main() {
      unsigned short s = 5;
      std::cout << byteswap(s) << std::endl;
      unsigned int i = 7;
      // std::cout << byteswap(i) << std::endl; // error
    }
    

提交回复
热议问题