alibaba / yalantinglibs

A collection of modern C++ libraries, include coro_rpc, struct_pack, struct_json, struct_xml, struct_pb, easylog, async_simple
https://alibaba.github.io/yalantinglibs/
Apache License 2.0
1.53k stars 239 forks source link

Compile error when class contains std::unique_ptr<base> #602

Closed WeaveAche closed 8 months ago

WeaveAche commented 8 months ago

Search before asking

What happened + What you expected to happen

Compilation error when a class contains std::unique_ptr but works fine otherwise. Expect to compile in both cases.

Reproduction way

base.hpp

#pragma once
#include <bits/stdc++.h>

struct base {
  virtual uint32_t get_struct_pack_id() const = 0;
  virtual std::string get_name() const = 0;
  static std::unique_ptr<base> deserialize(std::string &);
};

derived.hpp

#include <bits/stdc++.h>
#include "ylt/struct_pack.hpp"
#include "base.hpp"

struct derived : public base {
  std::unique_ptr<base> member;
  //std::string member;

  derived() = default;

  uint32_t get_struct_pack_id() const override;

  std::string get_name() const override {
      return "derived";
  }
};
STRUCT_PACK_REFL(derived, member);

common.cpp

#include "base.hpp"
#include "derived.hpp"
#include "ylt/struct_pack.hpp"

STRUCT_PACK_DERIVED_IMPL(base, derived)

std::unique_ptr<base> base::deserialize(std::string &serialized) {
    return struct_pack::deserialize_derived_class<base, derived>(serialized).value();
}

main.cpp

#include "base.hpp"
#include "derived.hpp"

int main() {
    derived d{};
    auto s = struct_pack::serialize<std::string>(d);
    auto n = base::deserialize(s);
}

Compiled with g++ main.cpp common.cpp -I yalantinglibs/include. The compilation fails when derived::member is std::unique_ptr<base> but works fine if it is anything else.

Anything else

No

Are you willing to submit a PR?

WeaveAche commented 8 months ago

base is an empty struct here so the assertion on packer.hpp:419 fails. But since struct_pack already supports serializing std::unique_ptr<base> it should do it in this case too?

WeaveAche commented 8 months ago

Ok this happens because the STRUCT_PACK_DERIVED_IMPL macro needs to be in the header file.