template specialization according to sizeof type

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

    Just for the sake of demonstrating enable_if in action, since you spoke about it:

    template 
    typename boost::enable_if_c< sizeof(T) == 2, T >::type
    swapIt(T& rhs) { return _byteswap_short(rhs); }
    
    template 
    typename boost::enable_if_c< sizeof(T) == 4, T >::type
    swapIt(T& rhs) { return _byteswap_long(rhs); }
    

    etc...

    And of course, instead of throwing, there is just no implementation if the type doesn't meet any of the requirement and thus you have a compile time error.

    Two notes:

    • Use of typename and ::type are mandatory
    • I used enable_if_c because my expression evaluates to a boolean value directly, whereas enable_if requires a type containing a ::value member which is a boolean.

提交回复
热议问题