从派生班级的基类中陈述占用缓冲区
我想创建一个结构对象数组,每个对象都包含一个具有值的成员。但是,此值在对象之间的类型可能有所不同。由于尺寸不能有所不同,因此我决定将一个占位缓冲区放在基类中,我试图从模板到类型的派生类中别名。但这是行不通的:
#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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论