简体   繁体   中英

std::forward cannot convert brace-enclosed initializer list

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.

#include <iostream>
#include <sstream>
#include <cstring>

#define ESC "\033"

struct frame {
  public:
    frame(unsigned int w, unsigned int h) :
      m_w(w),
      m_h(h) {}

  private:
    unsigned int m_w, m_h;
};

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

  private:
    frame m_f0, m_f1;
};

int main() {
  frame f = {16, 16};

  screen s = {f, {16, 16}};

  return 0;
}

{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 , but make_from_tuple can be implemented as far back as or in C++14 .

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