[英]C++ Confusion about namespaces and aliasing: no nesting and no using directives
我不是在嘗試嵌套名稱空間,而是在標題中不使用using指令。 我正在嘗試使用另一個名稱來別名命名空間“名稱”。 在標題中,我有一個全名的全局空名稱空間。 我想為此名稱分配另一個名稱空間,然后用我的源填充它。 我不確定執行此操作的合適語法是什么。 這是我的頭文件中的示例。
#ifndef SOME_HEADER_H
#define SOME_HEADER_H
namespace SomeLongNamespaceHere {} // Empty Global
namespace SLNH = SomeLongNamespaceHere; // Alias
namespace slnh = SLNH; // another lowercase alias
namespace slnh { // Compiler Error:
// My Declarations Here!
class foo{};
}
#endif // SOME_HEADER_H
1>------ Build started: Project: FileTester, Configuration: Debug Win32 ------
1> include.cpp
1>c:\users\skilz80\documents\visual studio 2015\projects\filetester\filetester\include.h(8): error C2757: 'mfbid': a symbol with this name already exists and therefore this name cannot be used as a namespace name
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
我了解編譯器錯誤,但這不是問題所在。
但是,當我這樣做時:
namespace slnh{}
namespace slnh{
class foo{};
}
它編譯就好了。 我不確定是否誤解了名稱空間別名的確切含義和用途,或者是否使用的語法不正確。
我正在嘗試使用較短的版本代替較長的版本,以便用戶可以直接使用較短的版本,並且當它們懸停在較短的名稱空間上時,它將自動解析回較長的名稱空間,並可以通過諸如以下功能查看MSVS的智能感知或類似的東西。 如何實現或模仿我上面描述的行為?
您可以根據需要多次重新打開命名空間,這就是這樣做的原因:
namespace slnh{}
namespace slnh{
class foo{};
}
但是您不能使用別名相同的名稱重新聲明名稱空間,這是沖突的:
namespace SomeLongNamespaceHere {} // Empty Global
namespace SLNH = SomeLongNamespaceHere; // Alias
namespace slnh = SLNH; // another lowercase alias
//This namespace clashes with the alias above.
namespace slnh { // Compiler Error:
// My Declarations Here!
class foo{};
}
它不起作用,因為您要將同一個名稱與名稱空間和名稱空間別名相關聯。 這會沖突AFAIK。
編輯:無論如何您都不能使用別名來打開名稱空間。 因此無法完成。
可能的解決方法(根本不建議使用)是使用較短的名稱空間並放入using指令:
namespace SomeLongNamespace {
using namespace SLN;
}
namespace SLN {
//Populate here
class MyClass {};
}
SLN::MyClass ...; //works
SomeLongNamespace::MyClass ...; //works
另一個丑陋的解決方法是使用宏(也不推薦):
#define SLN SomeLongNamespace
僅保存一些擊鍵就可能是不好的,而宏是邪惡的,所以不要這樣做。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.