gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 04:55:03 26 4
gpt4 key购买 nike

我正在尝试为我的用户定义结构使用 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} });
}

我遇到编译问题:

error: no matching function for call to 'std::vector<EntryDef>::emplace_back'

最佳答案

comment通过 @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.

澄清问题。

另一种“修复”这个问题的方法是传递一个所需类型的右值作为构造函数的参数,而不是初始化列表:

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

称为:

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

实例 HERE .

关于C++ 如何将 emplace_back 用于用户定义的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53302655/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com