首页 > 解决方案 > 返回具有随机值的对象的模板函数

问题描述

我想要一个模板函数,它返回具有随机值的任何类的对象。我尝试了下面的函数,但它不起作用,因为tab它被读取为 auint32_t*而不是numberOfCallstype 的值序列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>,但我更喜欢拥有一个适用于所有内容的强大模板函数。

标签: c++templatesrandom

解决方案


推荐阅读