我正在尝试构造一个std::unique_ptr
指针,其中包含枚举和两个结构元素的并集:
struct button_t
{
std::uint8_t id;
std::uint16_t status;
};
struct led_t
{
std::uint8_t id;
std::uint16_t status;
};
struct message_t
{
enum class id_e : std::uint8_t { button_e, led_e } id;
union
{
button_t button;
led_t led;
};
message_t(message_t::id_e id, const button_t& button) : id(id), button(button) {}
message_t(message_t::id_e id, const led_t& led) : id(id), led(led) {}
};
当我尝试使用std::unique_ptr
构建std::make_unique
时,如下所示:
button_t button{56, 78};
typedef std::unique_ptr<message_t> p_msg_t;
auto msg = std::make_unique<p_msg_t>(message_t::id_e::button_event, button);
我收到以下编译错误:
error: no matching function for call to 'std::unique_ptr<message_t>::unique_ptr(message_t::id_e, button_t&)'
有人可以帮我确定问题所在吗?
答案 0 :(得分:1)
评论中已回答了这个问题。但请注意,您可以避免多余的类型&#39;参数,因为你可以从传递给构造函数的io对象推断它:
#include <cstdint>
#include <memory>
struct button_t
{
std::uint8_t id;
std::uint8_t status;
};
struct led_t
{
std::uint8_t id;
std::uint16_t status;
};
struct message_t
{
enum class id_e : std::uint8_t { button_e, led_e } id;
union
{
button_t button;
led_t led;
};
explicit message_t(const button_t& button)
: id(message_t::id_e::button_e)
, button(button)
{
}
explicit message_t(const led_t& led)
: id(message_t::id_e::led_e)
, led(led)
{
}
};
int main()
{
button_t button{56, 78};
auto msg = std::make_unique<message_t>(button);
msg = std::make_unique<message_t>(led_t { 43, 12 });
}