gpt4 book ai didi

c++ - unordered_map - 未定义模板的隐式实例化

转载 作者:行者123 更新时间:2023-11-30 04:19:10 43 4
gpt4 key购买 nike

我的 C++ 生锈了。我有一个成员变量是 unordered_map<some_enum_type, string> .

我正在尝试在类构造函数中填充 map 。我在这里做错了什么?

来 self 的标题:

#include <iostream>
#include <unordered_map>

using namespace std;

typedef enum{
GET,
POST,
PUT,
DELETE
}http_verb;

class CouchServer{
string host;
int port;
string dbname;
unordered_map<http_verb,string> req_types;
public:

我的构造函数实现:

 CouchServer::CouchServer(string host, int port, string dbname){
this->host = host;
this->port = port;
this->dbname = dbname;
this->req_types = {
{req_types[GET], "GET"},
{req_types[POST], "POST"},
{req_types[PUT], "PUT"},
{req_types[DELETE],"DELETE" }
};
}

更新:

阅读提供的答案和评论后,我将标题更改为:

    class CouchServer{
string host;
int port;
string dbname;
unordered_map<http_verb,string> req_types;
public:
CouchServer(std::string host, int port, std::string dbname)
: host(std::move(host))
, port(port)
, dbname(std::move(dbname))
, req_types{
{ http_verb::GET, "GET" },
{ http_verb::POST, "POST" },
{ http_verb::PUT, "PUT" },
{ http_verb::DELETE, "DELETE" }
}
{ }

同样的问题仍然存在。我应该提到我正在尝试使用 XCode 4 编译此代码,也就是说 Apple LLVM 编译器 4.2

最佳答案

这可能是编译器的限制。类似的东西在 GCC 4.7.2 中对我有用,标准确实说有一个赋值运算符接受一个初始化列表。

但是你不应该在构造函数中做任何赋值!使用构造函数初始化器列表要好得多:

CouchServer(std::string host, int port, std::string dbname)
: host(std::move(host))
, port(port)
, dbname(std::move(dbname))
, req_types { { http_verb::GET, "GET" } } // etc.
{ }

(当然,永远、永远、永远不要在头文件中说abusing namespace std;。)

你必须为你的枚举专门化std::hash;转换为合适的整数类型应该可以解决问题。

关于c++ - unordered_map - 未定义模板的隐式实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16005049/

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