简体   繁体   中英

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;

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM