未命名的命名空间 [英] unnamed namespace

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

问题描述

标准规定的具体含义是什么

What does it exactly mean when the Standard states

$7.3.1.1/2 -》静态的使用声明时不推荐使用关键字命名空间范围内的变量(参见附件 D);未命名的命名空间提供了一个更好的选择."

$7.3.1.1/2 - "The use of the static keyword is deprecated when declaring variables in a namespace scope (see annex D); the unnamed-namespace provides a superior alternative."

我已经提到了 这个,但它没有涵盖我正在寻找的内容为.

I have referred this but it does not cover what I am looking for.

有没有一个例子清楚地证明了优越性.

Is there an example where the superiority is clearly demonstrated.

注意:我知道未命名的命名空间如何使外部变量在翻译单元中可见,但对其他翻译单元隐藏它们.但这篇文章的重点是关于静态命名空间范围"的名称(例如全局静态变量)

NB: I know about how unnamed namespaces can make extern variables visible in the translation unit and yet hide them from other translation units. But the point of this post is about 'static namespace scope' names (e.g global static variables)

推荐答案

究竟是什么意思?

技术上已弃用意味着未来的标准可能会删除该功能.

What does it exactly mean?

Technically deprecated means that a future standard may remove the feature.

实际上这不会发生,因为需要支持旧代码.

In practice that isn't going to happen, because of the need to support old code.

所以在实践中它的意思是强烈劝阻".

So in practice it means, "strongly discouraged".

未命名的命名空间通常更好,因为您在该命名空间中的内容可以具有外部链接.

An unnamed namespace is generally superior because what you have in that namespace can have external linkage.

在 C++98 中,对于可以是模板参数的东西,外部链接是必需的,例如,如果你想在 char const* 上进行模板化,它必须是指向 char<的指针/code> 具有外部链接.

In C++98 external linkage is necessary for things that can be template parameters, e.g., if you want to templatize on a char const*, it must be pointer to char that has external linkage.

#include <iostream>

// Compile with "-D LINKAGE=static" to see problem with "static"
#ifndef LINKAGE
#   define LINKAGE extern
#endif

template< char const* s >
void foo()
{
    std::cout << s << std::endl;
}

namespace {
    LINKAGE char const message[] = "Hello, world!";
}  // namespace anon

int main()
{
    foo<message>();
}

也就是说,static 也没有被函数弃用,这有点不一致.

That said, it's a bit inconsistent that static isn't also deprecated for functions.

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

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