IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    有效利用标准库提供的type_traits,让程序在编译时作出分支选择

    Hallelujah发表于 2016-04-28 09:50:00
    love 0
    让程序中的简单if-else在编译期间决定

    ex. 1 /*
     2  * =====================================================================================
     3  *
     4  *       Filename:  3.cpp
     5  *
     6  *    Description:  
     7  *
     8  *        Version:  1.0
     9  *        Created:  03/01/2016 11:38:53 AM
    10  *       Revision:  none
    11  *       Compiler:  gcc
    12  *
    13  *         Author:  shih (Hallelujah), sh19871122@gmail.com
    14  *   Organization:  
    15  *
    16  * =====================================================================================
    17  */
    18 
    19 #include <stdio.h>
    20 #include <stdint.h>
    21 #include <iostream>
    22 #include <type_traits>
    23 
    24 template<typename T>
    25 struct is_swapable
    26 {
    27     static const bool value = std::is_integral<T>::value && sizeof(T) >= 2;
    28 };
    29 
    30 template<typename T>
    31 T byte_swap(T value, std::true_type)
    32 {
    33    uint8_t *bytes = reinterpret_cast<uint8_t *>(&value);
    34    for (std::size_t i = 0; i < sizeof(T)/2; ++i)
    35    {   
    36        uint8_t v = bytes[i];
    37        bytes[i] = bytes[sizeof(T) - 1 - i]; 
    38        bytes[sizeof(T) -1 -i] = v;
    39    }   
    40    return value;
    41 }
    42 
    43 template<typename T>
    44 T byte_swap(T value, std::false_type)
    45 {
    46     return value;
    47 }
    48 
    49 template<typename T>
    50 T byte_swap(T value)
    51 {
    52     return byte_swap(value, std::integral_constant<bool, is_swapable<T>::value>());
    53 }
    54 
    55 int main(int argc, const char *argv[])
    56 {
    57     int a = 0x11223344;
    58     long b = 0x4455221112345678;
    59     std::cout << std::hex << a << " " << b << std::endl;
    60     std::cout << std::hex << byte_swap(a) << " " << byte_swap(b) << std::endl;
    61     uint8_t c = 0x11;
    62     char *d = "hello world";
    63     std::cout << std::hex << byte_swap(c) << " " << byte_swap(d) << std::endl;
    64     return 0;
    65 }
    66 


    Hallelujah 2016-04-28 17:50 发表评论


沪ICP备19023445号-2号
友情链接