来自Variadic模板的参考的默认构造元组

发布于 2025-01-18 09:44:17 字数 628 浏览 3 评论 0原文

template<typename... T>
struct RoundRobin
{
    // Dangling references
    RoundRobin() : choices{std::forward_as_tuple(T{}...)}
    {}

    // Expected behaviour
    RoundRobin(std::in_place_t, T&... c) : choices{std::forward_as_tuple(c...)}
    {}

    std::tuple<T&...> choices;
};

struct Choice {};

// OK
Choice c1, c2, c3;
RoundRobin good_robin(std::in_place, c1, c2, c3);

// NOT OK
RoundRobin<Choice, Choice, Choice> bad_robin;

我希望提供默认构造以下结构的能力(以及注入相应的选择)。

然而,在默认构造之后,选择元组会使用看似悬空的引用进行初始化,任何访问尝试都会导致段错误。

无论如何,我可以默认构造我的选择元组(并维护引用注入的现有功能)吗?

谢谢

template<typename... T>
struct RoundRobin
{
    // Dangling references
    RoundRobin() : choices{std::forward_as_tuple(T{}...)}
    {}

    // Expected behaviour
    RoundRobin(std::in_place_t, T&... c) : choices{std::forward_as_tuple(c...)}
    {}

    std::tuple<T&...> choices;
};

struct Choice {};

// OK
Choice c1, c2, c3;
RoundRobin good_robin(std::in_place, c1, c2, c3);

// NOT OK
RoundRobin<Choice, Choice, Choice> bad_robin;

I would like the provide the ability to both default construct the following struct (as well as inject respective choices).

After default construction, however, the choices tuple is initialized with seemingly dangling references and any access attempts result in a segfault.

Is there anyway I can default construct my choices tuple (and maintain the existing functionality of reference injection)?

Thanks

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

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

迷爱 2025-01-25 09:44:17

我建议将成员元组更改为不添加参考,并使用ctad:

template<typename... Ts>
struct RoundRobin
{
    RoundRobin() : choices{Ts{}...} {}

    // Expected behaviour
    RoundRobin(std::in_place_t, Ts&... c) : choices{std::forward_as_tuple(c...)}
    {}

    std::tuple<Ts...> choices;
};

template <typename... Ts>
RoundRobin(std::in_place_t, Ts&...) -> RoundRobin<Ts&...>;

demo

I suggest to change member tuple to not add reference, and use CTAD:

template<typename... Ts>
struct RoundRobin
{
    RoundRobin() : choices{Ts{}...} {}

    // Expected behaviour
    RoundRobin(std::in_place_t, Ts&... c) : choices{std::forward_as_tuple(c...)}
    {}

    std::tuple<Ts...> choices;
};

template <typename... Ts>
RoundRobin(std::in_place_t, Ts&...) -> RoundRobin<Ts&...>;

Demo.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文