注入命名空间实验性的std [英] Inject namespace experimental to std

查看:74
本文介绍了注入命名空间实验性的std的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将名称空间 std :: experimental 注入到 std 中是不好的选择吗?

 命名空间std 
{
命名空间实验性
{
}
使用命名空间实验
}

#include<实验性/可选>

int main()
{
std :: optional<整数> o;
返回0;
}

或更现代的形式:

  #if __has_include(< optional>)
#include< optional>
#elif __has_include(< experimental / optional>)
#include< experimental / optional>
命名空间std
{
使用命名空间实验性;
}
#else
#error!
#endif

int main()
{
std :: optional<整数> o;
返回0;
}

打算引入 std :: experimental 子命名空间很清楚,因为 std :: experimental 当前包含大量的。我认为他们很可能都将迁移到 namespace std 而不进行任何实质性更改,并且当前编写的用户代码可以依靠此(我完全错了吗?)。否则,所有这些代码都应该重构为将来从 std :: experimental :: 更改为 std ::

问题在于生产代码和不太严重的代码。

解决方案

听起来像个坏主意。



首先,这是不确定的行为。标准草案N4140说:


[namespace.std] / 1:行为如果C ++程序的声明或定义添加到命名空间 std 或命名空间 std 中的命名空间,则未定义指定。 [...]


using指令是一种声明,因此UB是当天的订单。



其次, std :: experimental 中的内容可能会发生很大变化。您可能会发现,将内容移至 std 时,您的代码仍然可以编译,但操作方式完全不同。这只是自找麻烦,尤其是在生产代码中。


Is it bad or good parctice to inject namespace std::experimental into std like following?

namespace std
{
namespace experimental
{
}
using namespace experimental;    
}

#include <experimental/optional>

int main()
{
    std::optional< int > o;
    return 0;
}

Or even in more modern form:

#if __has_include(<optional>)
# include <optional>
#elif __has_include(<experimental/optional>)
# include <experimental/optional>
namespace std
{
using namespace experimental;    
}
#else
#error !
#endif

int main()
{
    std::optional< int > o;
    return 0;
}

The intention to introduce std::experimental "sub-namespace" is clear because std::experimental currently contains a plenty of new libraries. I think it is very likely all them will migrate into namespace std without any substantial changes and user code written currently can rely upon this (am I totally wrong?). Otherwise all this code should be refactored to change from std::experimental:: to std:: in the future. It is not big deal, but there may be reasons not to do so.

The question is about both production code and not-too-serious code.

解决方案

Sounds like a bad idea.

First off, this is undefined behaviour. Standards draft N4140 says:

[namespace.std]/1: The behavior of a C++ program is undefined if it adds declarations or definitions to namespace std or to a namespace within namespace std unless otherwise specified. [...]

A using-directive is a kind of declaration, so UB is the order for the day.

Secondly, things in std::experimental are very much subject to change. You might find that when things are moved into std proper that your code still compiles, but doesn't act in quite the same way. This is just asking for trouble, especially in production code.

这篇关于注入命名空间实验性的std的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆