std::forward cannot convert brace-enclosed initializer list

前端 未结 1 2046
北恋
北恋 2021-01-16 16:07

Why can\'t struct screen not initialize the frame struct properly?

What I want is to initialize the screen struct and directly initialize the 2 frame structs as well

相关标签:
1条回答
  • 2021-01-16 17:08

    {16, 16} has no type. If used in a context to initialize something with a type, it initializes that thing.

    Constructor arguments have a type. Deduced template constructor arguments get their type from the argument passed. But {16,16} has no type, so it cannot deduce a type from something that lacks a type.

    Your second problem is this:

      template<typename ... Args>
      screen(Args && ... args0, Args && ... args1) :
        m_f0(std::forward<Args>(args0)...),
        m_f1(std::forward<Args>(args1)...) {}
    

    C++ won't deduce Args... for you here. It will only deduce an argument pack if it is the last arguments in the function call, and here Args... is both the last and not the last, so it won't be deduced.

    Now you can use make from tuple to some extent:

    template<class...Args0, class...Args1>
    screen( std::tuple<Args0...> args0, std::tuple<Args1...> args1 ):
      m_f0(std::make_from_tuple<frame>(std::move(args0))),
      m_f1(std::make_from_tuple<frame>(std::move(args1)))
    {}
    

    which gets you a touch closer (but not close enough). At the call site you'd do:

    screen s = {std::forward_as_tuple(f), std::forward_as_tuple(16, 16)};
    

    and it should now work.

    This uses c++17, but make_from_tuple can be implemented as far back as c++11 or in C++14.

    0 讨论(0)
提交回复
热议问题