gpt4 book ai didi

c++ - 硬编码对,三元组......值的最优雅方式

转载 作者:搜寻专家 更新时间:2023-10-31 02:22:08 24 4
gpt4 key购买 nike

我有一个枚举。

对于这个枚举中的每个值,我需要将一些数据与其相关联(实际上在这种情况下,它是一个整数,但我想更笼统地了解,例如 2 个整数值,或 2 个字符串等)。

用户无法访问这些值。在逆向工程的情况下,嗯,不能做太多,但它应该要求用户付出一些努力来实际修改它。所以它不能在配置文件或数据库等中。

所以我在想:

  1. 对它们进行硬编码,但在这种情况下,最优雅(最不可怕)的方法是什么?只需在命名空间中硬编码一对三元组,然后将其存储在哈希 [enumValue]->[struct]?
  2. 将其存储在一个将被编译为资源文件的文件中(虽然这可以通过一些工具访问,但它需要用户付出更多的努力)。如果有必要,我什至可以做一个校验和来确保它没有被修改?

你有什么想法?

总而言之,我有一个枚举,其中包含 VAL1、VAL2 ...

我想像这样联系:

VAL1 的长度为 5,名称为“foo”VAL2 的长度为 8,名称为“bar”

虽然我可能完全错过了其他简单的解决方案

最佳答案

此代码改编 self 不久前在另一篇 stackoverflow 帖子上找到的解决方案 - 如果有人能再次找到原始链接,我会将其包括在内以表彰他们。

我有一个类似的问题,我想将一个 string 与每个枚举值相关联。为您的一对值的情况稍微调整该代码我明白了。

template<typename T> class EnumParser
{
private:
std::map<T, std::pair<int, std::string>> _map_enum_keyed; // Map with enum values as keys

public:
EnumParser(); // Unspecified constructor
T Enum(const std::string &key) const; // Get the enum value for the given string key
std::pair<int, std::string> Value(const T &key) const; // Get the string value of the given enum key
};

// Template definitions

template<typename T>
std::pair<int, std::string> EnumParser<T>::Value(const T &key) const
{
const auto &iterator = this->_map_enum_keyed.find(key);
if(iterator == this->_map_enum_keyed.end())
{
throw std::runtime_error("EnumParser::Value(const T &key) - error 1 - Could not find key");
}
return iterator->second;
}

然后您可以在与 header 关联的 cpp 文件中使用它使用那个 enum

template<>EnumParser<YOUR_ENUM>::EnumParser()
{
this->_map_enum_keyed = {
{YOUR_ENUM::Value1, std::make_pair(5, "foo")},
{YOUR_ENUM::Value2, std::make_pair(8, "bar")},
};
}

您可以通过添加第二个模板参数并将我使用 std::pair 的地方替换为第二个模板来使其更通用。

这在想要将 enumstd::string 相关联时特别有用,因为您可以使用 std::string< 添加第二个映射 作为键,模板参数作为值。通过简单地反转原始映射,您可以将 string 转换为 enum 以及能够将 enum 转换为 字符串

关于c++ - 硬编码对,三元组......值的最优雅方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30641858/

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