1

I am trying to make use of emplace_back for my user defined structure:

#include <cstdint>
#include <vector>
#include <string>

struct IDNumber
{
    IDNumber(std::vector<int> d) : id(d){}
    std::vector<int> id;
};
struct Def
{
    Def(std::initializer_list<int> id) : mid(id){}
    IDNumber mid;
};

struct Student
{
    std::vector<Def> ent;
};

int main()

{
 Student a;
 a.ent.emplace_back({ {2000} });
}

I get compilation issues:

error: no matching function for call to 'std::vector<EntryDef>::emplace_back'
5
  • 5
    Your first argument to your constructor is std::initializer_list<int> yet you pass { {2}, 1 }? Commented Nov 14, 2018 at 14:38
  • I tried to change the line - a.ent.emplace_back({2,1,2}, FType::FD_NONE, Fmt::FMT_NONE, RWProp::PROP_RO, FId(0,TTypes::TYPE_NONE)); - but still I get the compilation issue - am I missing something?
    – Programmer
    Commented Nov 14, 2018 at 14:41
  • 4
    emplace_back is function template which tries to deduce the types of arguments. an initializer list does not have a type, so deduction fails. Use std::initializer_list<int>{ 2, 1 }. Commented Nov 14, 2018 at 14:42
  • @CoryKramer what is wrong with list-initializing the first int? Commented Nov 14, 2018 at 14:44
  • @PiotrSkotnicki yeah, they kind of messed up initializer_list
    – bolov
    Commented Nov 14, 2018 at 15:00

1 Answer 1

1

The comment by @PiotrSkotnicki:

emplace_back is function template which tries to deduce the types of arguments. an initializer list does not have a type, so deduction fails.

Clarifies the problem.

An alternative way to "fix" this issue is to pass an rvalue of the needed type as argument of the constructor, instead of the initializer list:

EntryDef(ID &&id, FType ft, … ) : mid(std::forward<ID>(id)), ftype(ft), … {}

Called as:

Def a;
a.ent.emplace_back(ID{ 2, 1 }, FType::FD_NONE, …);

Live example HERE.

Not the answer you're looking for? Browse other questions tagged or ask your own question.