gpt4 book ai didi

使用 getter 和 setter 存储全局 std::string 标签的 C++ 策略

转载 作者:行者123 更新时间:2023-11-28 00:35:55 25 4
gpt4 key购买 nike

在我正在处理的 C++ 项目中,我需要跟踪标签。该标签仅存储一个 std::string,它附加到写入各种文件的结果,以便可以将结果映射到已实现算法的特定阶段。 p>

以下是跟踪标签机制的要求:

  • 所有翻译单位都需要访问此标签
  • 标签必须能够在运行时修改
  • 需要通过 getter/setter 函数控制对标签的访问
  • 总是只需要 1 个标签

这并不难实现。但是,尽管如此,我在这里提出这个问题是因为我怀疑这是通常做的事情 --- 或者至少与通常做的事情非常相似。

我能想到的最好的解决方案是有一个像下面这样的类,然后在任何地方都包含接口(interface):

class Label {    
public:
static std::string get();
static int set(std::string s);
private:
static std::string label;
};

std::string Label::get() { return label; }

int Label::set(std::string s) {
if( /* OK to change to "s" */ ) {
label = s;
return 0;
}
return 1;
}

std::string Label::label = "";

因为总是恰好有 1 个这样的标签,所以似乎应该有比创建类更好的解决方案。有什么建议吗?

最佳答案

我想知道更广泛的类是否有更多用途,例如:

template <class T>
class cond_write {
T val;
std::function<bool()> c;
public:
template <class Cond>
cond_write(T const &t, Cond c): val(t), c(c) {}

cond_write &operator=(T const &t) {
if (c())
val=t;
return *this;
}

operator T() const { return val; }
};

然后您将使用(在您的情况下)std::string 和一个 lambda 来实例化它,该 lambda 用于表示可以发生写入的条件。

代替 getset,您只需分配给它,或将其用作 T (std::string,在你的情况下)。例如:

cond_write<std::string> label("Initial label", []() { return whatever(); });

// equivalent to label.set("This might be the new label");
label="This might be the new label";

// equivalent to std::string new_label = label.get();
std::string new_label=label;

关于使用 getter 和 setter 存储全局 std::string 标签的 C++ 策略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20963319/

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