Передача параметров Args из конструктора пользовательского шаблона в конструктор контейнераC++

Программы на C++. Форум разработчиков
Anonymous
Передача параметров Args из конструктора пользовательского шаблона в конструктор контейнера

Сообщение Anonymous »

Я пытаюсь передать параметры Args из шаблона в контейнер вызовом deque.emplace_back()
например,

Код: Выделить всё

class Collection
{
public:
template 
Collection(const std::string& name, Args...  entries)
: m_name(name)
{
m_entries.emplace_back(entries...);  // Here!!!! Entry, Entry, Entry added to deque
}

private:
std::string m_name;
std::deque m_entries;
};

Collection collection1
{
"my collection",
Entry{4},
Entry{5.5},
Entry2{1, 2}
};

По сути, мне хотелось бы иметь несколько экземпляров Collection с разными наборами записей (разные типы, разные числа). И хочу создать универсальный конструктор для всех возможных комбинаций.

Код: Выделить всё

emplace_back
 — шаблон с перегрузкой параметров Args

Код: Выделить всё

template< class... Args >
reference emplace_back( Args&&... args );
Поэтому я думаю, что это может занять список объектов. Но это не скомпилировано.
С ошибкой

Код: Выделить всё

/opt/compiler-explorer/gcc-13.2.0/include/c++/13.2.0/bits/new_allocator.h: In instantiation of 'void std::__new_allocator::construct(_Up*, _Args&& ...) [with _Up = std::any; _Args = {Entry&, Entry&, Entry2&}; _Tp = std::any]':
/opt/compiler-explorer/gcc-13.2.0/include/c++/13.2.0/bits/alloc_traits.h:537:17:   required from 'static void std::allocator_traits::construct(allocator_type&, _Up*, _Args&& ...) [with _Up = std::any; _Args = {Entry&, Entry&, Entry2&}; _Tp = std::any; allocator_type = std::allocator]'
/opt/compiler-explorer/gcc-13.2.0/include/c++/13.2.0/bits/deque.tcc:170:30:   required from 'std::deque::reference std::deque::emplace_back(_Args&& ...) [with _Args = {Entry&, Entry&, Entry2&}; _Tp = std::any; _Alloc = std::allocator; reference = std::any&]'
:44:31:   required from 'Collection::Collection(const std::string&, Args ...) [with Args = {Entry, Entry, Entry2}; std::string = std::__cxx11::basic_string]'
:58:1:   required from here
/opt/compiler-explorer/gcc-13.2.0/include/c++/13.2.0/bits/new_allocator.h:187:11: error: no matching function for call to 'std::any::any(Entry&, Entry&, Entry2&)'
187 |         { ::new((void *)__p) _Up(std::forward(__args)...); }
|           ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Полный пример Godbolt https://godbolt.org/z/YoPPToEdr

Я бы признателен за совет, как заставить это работать.

Спасибо.s

Подробнее здесь: https://stackoverflow.com/questions/784 ... r-construc

Вернуться в «C++»