gpt4 book ai didi

c++ - 在 C++ 中存储常量

转载 作者:搜寻专家 更新时间:2023-10-31 00:16:46 26 4
gpt4 key购买 nike

我想将程序的目录结构存储为常量字符串结构,但 C++ 不允许我以任何直观的方式进行。

所以这是行不通的:

struct DirStructure {
static const std::string entities = "./entities";
static const std::string scripts = "./scripts";
}

这也不是:

struct DirStructure {
static const std::string entities() const = { return "./entities"; }
static const std::string scripts() const { return "./scripts"; }
}

(实际上它没有常量,但我不太喜欢它)。

这个有效:

namespace DirStructure {
static const std::string entities = "./entities";
static const std::string scripts = "./scripts";
}

但它还有一些其他问题。

处理此类问题的标准方法是什么(假设我宁愿避免#define MY_SCRIPTS_DIR_PATH "./scripts")?

最佳答案

想到了三种方法。前两个类似于您的方法,后者是我可能使用的更典型的方法

#1 - 匿名命名空间 + 内联 constexpr 函数

就我的目的而言,这解决了除 1 个问题之外的所有问题:

#include <string>

namespace DirStructure {
namespace {
inline constexpr char const* const entities() { return "./entities"; }
}
};

int main()
{
std::string e = DirStructure::entities();
}

剩下的一个问题是字符串文字不能包含嵌入的 NUL 字符(这在文件路径的情况下不是问题)。

#2 - 聚合初始化

另一种方法可能是

#include <string>

struct DirStructure
{
std::string entities, scripts;
};

inline static const DirStructure& Config()
{
static DirStructure _s = { "./entities", "./scripts" };
return _s;
}

int main()
{
std::string e = Config().entities;
}

#3 - 表达类型

通常我自己使用的东西类似于:

#include <string>
#include <map>
#include <boost/filesystem.hpp>

int main()
{
const std::map<std::string, boost::filesystem::path> DirStructure = {
{ "entities", "./entities" },
{ "scripts", "./scripts" }
};
auto const& e = DirStructure.at("entities");
}

关于c++ - 在 C++ 中存储常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15185699/

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