简体   繁体   English

C++ 如何将 emplace_back 用于用户定义的结构

[英]C++ how to use emplace_back for user defined structure

I am trying to make use of emplace_back for my user defined structure:我正在尝试将 emplace_back 用于我的用户定义结构:

#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'

The comment by @PiotrSkotnicki : @PiotrSkotnicki评论

emplace_back is function template which tries to deduce the types of arguments. emplace_back是函数模板,它试图推断参数的类型。 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 .现场示例在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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