一 概述
bit_cast是C++20支持的按字节进行转换的方法,如:
auto a = std::bit_cast<std::array<char, sizeof(p)>>(p);
二 代码分析
1.bit_cast.hpp:
#pragma once
#include <cstring>
#include <type_traits>
template <class To, class From>
typename std::enable_if_t<(sizeof(To) == sizeof(From))
&& std::is_trivially_copyable_v<From>
&& std::is_trivially_copyable_v<To>,
To> bit_cast(const From &src) {
static_assert(std::is_trivially_constructible_v<To>, "require constructible.");
To dst;
std::memcpy(&dst, &src, sizeof(To));
return dst;
}
(1)std::memcpy类似C语言的memcpy,需要包含头文件cstring;
(2)std::enable_if_t是C++17支持的条件编译,如果std::enable_if_t<条件,类型>中的条件为true,那么编译器选择设置的类型;
(3)std::is_trivially_copyable_v用来判断某种类型是否可以复制;
(4)std::is_trivially_constructible_v用来判断某种类型是否有缺省构造函数;
(5)static_assert用于编译时判断。
2.测试代码test.cpp:
#include <stdio.h>
#include <iostream>
#include "bit_array.hpp"
void fun() {
std::cout << "I am fun." << std::endl;
}
int main() {
long x = bit_cast<long, decltype(&fun)>(fun);
printf("fun address:0x%0x\n", fun);
printf("fun address with bit cast:0x%0x\n", x);
decltype(&fun) kk;
kk = fun;
kk(); // call fun
return 0;
}
(1)decltype(&fun)用来获取fun函数类型;
(2)通过bit_cast转换后x和fun的地址一致。
(3)kk是fun函数定义的类型,使用kk()就是调用fun函数。
3.编译:
使用C++17编译
g++ -std=c++17 -g -o Test test.cpp -I ./