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

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

问题描述

当标准规定

是什么意思


$ 7.3.1.1 / 2 - 使用静态
当在命名空间范围中声明
变量时,不推荐使用关键字(参见
附件D);未命名命名空间
提供了一个更好的替代方案


我已引用,但它不包括我正在寻找的东西。



是否有一个例子,其优势被清楚地证明。



NB:我知道未命名的命名空间如何使外部变量在翻译单元中可见,并且将其隐藏在其他翻译单元之外。但这个帖子的意思是关于静态命名空间范围的名称(例如全局静态变量)

解决方案





在实践中,这意味着强烈不鼓励。



未命名命名空间的优越性示例



未命名的命名空间通常是优越的,因为您在该命名空间中拥有的可以具有外部链接。 / p>

在C ++ 98中,外部链接对于可以是模板参数的事情是必要的,例如,如果你想在 char const * / code>,它必须是有外部链接的 char 的指针。

 code> #include< iostream> 

//编译-D LINKAGE = static查看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!
} //命名空间anon

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

也就是说, static 不会被函数弃用。


What does it exactly mean when the Standard states

$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".

Example of superiority of unnamed namespace

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

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>();
}

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

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

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