gpt4 book ai didi

c++ - 将抽象类传递给 i/o 宏

转载 作者:太空狗 更新时间:2023-10-29 23:07:23 25 4
gpt4 key购买 nike

我通过确保继承层次结构中的类实现虚拟读写功能来实现序列化:

class base
{
...

virtual void read(std::istream&)=0;
virtual void write(std::ostream&) const=0;
virtual std::string is_a() const;
};

BEGIN_NAMESPACE_1(io)
SERIALISE(base)
END_NAMESPACE_1

其中宏“SERIALISE”实现了“序列化”和“反序列化”函数的重载,以允许通过基类指针轻松进行 i/o:

#define SERIALISE(TYPE)\
void deserialise( boost::shared_ptr<TYPE>& dat, std::istream& ifs )\
{\
std::string type;\
read(type, ifs);\
\
dat = TYPE::make_##TYPE(type);\
dat->read(ifs);\
}\
\
void serialise( const boost::shared_ptr<TYPE>& dat, std::ofstream& ofs )\
{\
write(dat->is_a(), ofs);\
dat->write(ofs);\
}

但是,如果基类包含纯虚函数,我会收到编译器错误“无法分配抽象类型“base”的对象,因为以下函数在“base”中是纯函数...”,大概是因为编译器试图当类名传递给宏调用时实例化抽象基类。有没有办法挽救这个 I/O 设计?

最佳答案

您不能实例化抽象基类或将其用作函数的值参数。

template explicit shared_ptr(Y * p); Requirements: p must be convertible to T *. Y must be a complete type. The expression delete p must be well-formed, must not invoke undefined behavior, and must not throw exceptions.

Effects: Constructs a shared_ptr that owns the pointer p.

Postconditions: use_count() == 1 && get() == p.

Throws: std::bad_alloc, or an implementation-defined exception when a resource other than memory could not be obtained.

Exception safety: If an exception is thrown, delete p is called.

Notes: p must be a pointer to an object that was allocated via a C++ new expression or be 0. The postcondition that use count is 1 holds even if p is 0; invoking delete on a pointer that has a value of 0 is harmless.

在这种情况下,编译器不必将模板 shared_ptr 解析为内部具有 TYPE 类型的值,因为它们永远无法实例化。

关于c++ - 将抽象类传递给 i/o 宏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13011640/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com