从派生班级的基类中陈述占用缓冲区

发布于 2025-01-27 22:13:01 字数 1137 浏览 2 评论 0原文

我想创建一个结构对象数组,每个对象都包含一个具有值的成员。但是,此值在对象之间的类型可能有所不同。由于尺寸不能有所不同,因此我决定将一个占位缓冲区放在基类中,我试图从模板到类型的派生类中别名。但这是行不通的:

#include <iostream>
#include <string>

struct some_struct_base
{
    std::string name_;
    char placeholder_[sizeof(std::string)];
    some_struct_base* next_;
    some_struct_base* prev_;
};

template <typename T>
struct some_struct : some_struct_base
{
    using val = static_cast<T>(some_struct_base::placeholder_);
};


int main()
{
    std::cout << sizeof(some_struct<std::string>) << std::endl;

    some_struct_base arr[10]; // <-- this is why the size needs to be fixed
    std::cout << static_cast<some_struct<std::string>>(arr[10]).val << std::endl; // <-- allow this
}

产量:

<source>:99:17: error: expected type-specifier before 'static_cast'
   99 |     using val = static_cast<T>(some_struct_base::placeholder_);
      |                 ^~~~~~~~~~~

我可以中途理解这一点,因为Val定义了类型而不是可变名称。但是我不想向派生类介绍新成员(例如参考成员,例如),因为这需要在嵌入式系统上运行,而另外4个字节已经要求太多。

如何使用最小空间 /没有其他开销来实现这一目标?

I want to create an array of struct objects that each contain a member which holds a value. However, this value might differ in its type from object to object. As the size can't vary I decided to put a placeholding buffer in the base class which I try to alias from a templated-to-type derived class. But this doesn't work:

#include <iostream>
#include <string>

struct some_struct_base
{
    std::string name_;
    char placeholder_[sizeof(std::string)];
    some_struct_base* next_;
    some_struct_base* prev_;
};

template <typename T>
struct some_struct : some_struct_base
{
    using val = static_cast<T>(some_struct_base::placeholder_);
};


int main()
{
    std::cout << sizeof(some_struct<std::string>) << std::endl;

    some_struct_base arr[10]; // <-- this is why the size needs to be fixed
    std::cout << static_cast<some_struct<std::string>>(arr[10]).val << std::endl; // <-- allow this
}

yields:

<source>:99:17: error: expected type-specifier before 'static_cast'
   99 |     using val = static_cast<T>(some_struct_base::placeholder_);
      |                 ^~~~~~~~~~~

I can halfway understand this as val defines a type and not a variable name. But I don't want to introduce new members to the derived class (like a reference member e.g.) because this needs to run on embedded systems and another 4 bytes is already asking for too much.

How can I achieve this using minimal space / no additional overhead?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文