gpt4 book ai didi

c++ - 如何在std命名空间中引入一个struct

转载 作者:行者123 更新时间:2023-12-03 06:53:34 35 4
gpt4 key购买 nike

我们目前使用 C++11。C++11 中缺少 std::optional - 它已在 C++17 中引入。幸运的是,我找到了一个与 std::optional 具有相同接口(interface)并在 C++11 ( https://github.com/TartanLlama/optional )

中工作的实现

这在 namespace tl 中定义了 optional。所以,我可以这样使用它:

#include "optional.hpp"

tl::optional<int> to_int(string str) {
if (...) { return atoi(str); }
else { return tl::nullopt; }
}

但是,我正在寻找一种方法来调用它,就好像 std::optional 可用一样:

#include "optional.hpp"

std::optional<int> to_int(string str) {
if (...) { return atoi(str); }
else { return std::nullopt; }
}

这样,当我们切换到 C++17 时,我将不必将每个 tl::optional 替换为 std::optional。我只需将“optional.hpp” header 的内容替换为:

// optional.hpp 
// ------------
#include <optional.hpp>

今天,这个 header 实现为:

// optional.hpp 
// ------------
#include "tl/optional.hpp" // include the official header, when C++17 is available

我如何在这个 header 中创建某种别名,以便当我调用 std::optional 时它实际上会引用 tl::optional

  • 我不能修改tl/optional.hpp的原始代码。
  • 我不想使用宏

最佳答案

How to introduce a struct in the std namespace

通过向标准委员会提交提案。但在这种情况下,该类已被采用,因此您需要做的是开始使用新版本的标准来获取该类。

How can I create some sort of an alias in this header, so that when I call std::optional it will actually refer to the tl::optional ?

作为非标准库实现者,您不能将类引入 std 命名空间。

您可以取而代之的是您自己的命名空间中的别名:

namespace my_very_own {
using tl::optional; // change to std::optional when possible
}

关于c++ - 如何在std命名空间中引入一个struct,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64559346/

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