【发布时间】:2018-07-06 08:14:31
【问题描述】:
我有应该用 gcc 4.7 编译的代码, 对c++11的支持还不错,但是缺少c++14和c++17。
我想在我的代码中使用std::optional 和std::variant,
为 gcc 4.7 提供 boost::optional 和 boost::variant 的后备
实现这一目标的标准方法是什么?
我看到两种变体:
- 包装变体,它可能是宏,如:
#define VARIANT_TYPE boost::variant或namespace my_code { using variant = boost::variant } - 扩展
std命名空间
第一个不好,因为我的代码会使用my_code::variant,
而不是std::variant。第二个对我来说看起来更清楚。
2 在一般情况下可能是 UB What are the reasons that extending the std namespace is considered undefined behavior?
但是我的具体情况呢?我知道gcc 的确切版本有variant/optional,我可以在构建的配置阶段检查它。对于所有其他编译器/标准 c++ 库,我可以要求 c++17 支持,而不是使用我将 boost::optional 转换为 std::optional 的技巧。
我还能发现一些奇特的问题吗?
【问题讨论】:
-
切换实现的意义何在?只需无条件使用 boost。
-
我会做
using variant_type = std::variant;。为此避免使用宏。此外,除非标准允许,否则永远不要扩展std。 -
@HolyBlackCat 因为它是库,我不想为拥有
c++17兼容编译器的用户创建对 boost 的外部依赖。 -
@Galik 但对于特定的编译器和 libstdc++ 不适用于一般情况