更新时间:2023-02-11 21:18:21
// needed include files
#include <iostream> // for cout
#include <stdexcept> // for runtime_error
#include <cstring> // for memcpy
// generic template function that takes 3 arguments
// 1 destination object
// 2 source object
// 3 from which byte to start in the destination
template<class T1, class T2>
void replace_bytes ( T1& t1, const T2& t2, std::size_t k )
{
// at compile time, store the size of T1 type in t1_size
constexpr std::size_t t1_size = sizeof(T1);
// at compile time, store the size of T2 type in t2_size
constexpr std::size_t t2_size = sizeof(T2);
// if we copy t2 bytes to t1, do we run out of memory ?
if ( k + t2_size > t1_size )
{
throw std::runtime_error("Can't copy out of bounds.");
}
// do the copying, casting is required for proper pointer arithmitic
std::memcpy( (void*) (((char*)&t1)+k), (const void*) &t2, t2_size );
}
int main()
{
int x = 0;
char c = 10;
replace_bytes(x, c, 0);
std::cout << x << std::endl;
}
干净版本的代码(无注释):
Clean version of code (no comments):
#include <iostream>
#include <stdexcept>
#include <cstring>
template <class T1, class T2>
void replace_bytes ( T1& t1, const T2& t2, std::size_t k )
{
constexpr std::size_t t1_size = sizeof(T1);
constexpr std::size_t t2_size = sizeof(T2);
if ( k + t2_size > t1_size )
{
throw std::runtime_error("Can't copy out of bounds.");
}
std::memcpy( (void*) (((char*)&t1)+k), (const void*) &t2, t2_size );
}
int main()
{
int x = 0;
char c = 10;
replace_bytes(x, c, 0);
std::cout << x << std::endl;
}