c++ - 返回具有随机值的对象的模板函数
问题描述
我想要一个模板函数,它返回具有随机值的任何类的对象。我尝试了下面的函数,但它不起作用,因为tab
它被读取为 auint32_t*
而不是numberOfCalls
type 的值序列uint32_t
。
std::random_device rd;
template <typename Type>
Type RandomObject(void)
{
constexpr auto numberOfCalls = (sizeof(Type) + sizeof(uint32_t) - 1u)/sizeof(uint32_t);
uin32_t tab[numberOfCalls];
for (auto i = 0u; i < numberOfCalls; ++i)
tab[i] = rd();
return reinterpret_cast<Type>(tab);
}
这是我想做的事情的一个例子。
struct Test
{
uint64_t s;
uint64_t t;
uint32_t x;
uint32_t y;
uint32_t z;
};
int32_t main(void)
{
const auto foo = ::RandomObject<Test>();
// do things
return 0;
}
当然,我可以简单地实现RandomObject<Test>
,但我更喜欢拥有一个适用于所有内容的强大模板函数。
解决方案
推荐阅读
- python-requests - 如何从 url 获取部分数据,这些代码让我无法解码错误 python3.0
- python - 扑克移动庄家筹码
- javascript - 嗨为什么我不能让这个 Svg 使用 GSAP 在 codepen 上变形
- r - 在 R 中使用 tidyverse 的多条件 if/else 过滤器
- image-processing - 我正在尝试从头开始实现 Harris 角点检测算法,但无法实现非最大抑制
- python - 如何通过语句sqlite3 python 3.8对组中的行求和
- json - 使用 BigQueryToCloudStorageOperator 导出为 JSON
- excel - 使用选项卡名称作为特定单元格中的变量跳转到选项卡
- bash - /usr/bin/bash:尝试运行 Docker 相关脚本时无法执行二进制文件
- javascript - 替换字符串中的单词