【发布时间】:2012-08-16 15:12:21
【问题描述】:
我有这个:
// static enum of supported HttpRequest to match requestToString
static const enum HttpRequest {
GET,
POST,
PUT,
DELETE,
OPTIONS,
HEAD,
TRACE
};
// typedef for the HttpRequests Map
typedef boost::unordered_map<enum HttpRequest, const char*> HttpRequests;
// define the HttpRequest Map to get static list of supported requests
static const HttpRequests requestToString = map_list_of
(GET, "GET")
(POST, "POST")
(PUT, "PUT")
(DELETE, "DELETE")
(OPTIONS,"OPTIONS")
(HEAD, "HEAD")
(TRACE, "TRACE");
现在如果我打电话
requestToString.at(GET);
没关系,但是如果我调用一个不存在的键
requestToString.at(THIS_IS_NO_KNOWN_KEY);
它给出一个运行时异常并且整个过程中止..
防止这种情况的最佳方法是什么?是否有编译指示或什么,或者我应该用 try/catch 块或什么来“类 java”围绕它?
请亚历克斯
【问题讨论】:
-
static const enum???static和const在类型定义中有什么含义吗? -
不要认为在这种情况下实际上需要 const 但无论如何:-)
-
在这种情况下,
enum上的static和const毫无意义。 C++ 不是 Java。在 C++ 中,enums 是具有限制范围的整数类型。
标签: c++ exception boost try-catch unordered-map