簡體   English   中英

默認構造來自可變參數模板的引用元組

[英]Default construct tuple of references from variadic template

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;

我希望提供默認構造以下結構的能力(以及注入相應的選擇)。

然而,在默認構造之后, choices元組使用看似懸空的引用進行初始化,並且任何訪問嘗試都會導致段錯誤。

無論如何我可以默認構造我的choices元組(並保持引用注入的現有功能)?

謝謝

我建議將成員元組更改為不添加引用,並使用 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&...>;

演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM