![](/img/trans.png)
[英]Why is including “using namespace” into a header file a bad idea in C++?
[英]c++ including header file in unnamed namespace
我在工具包(具有各種可公開訪問的文件的文件)中使用了一個稱為Cache的類。 使用回調刷新緩存,這需要一個仿函數對象。 functor對象在我的工具包中調用Cache的一個函數,就是Cache的實例上的refresh()。
該實例位於工具包中未命名的命名空間內(因為我不希望客戶端直接訪問它)。
現在,我已經完成了所有工作,但是我真的希望Cache具有自己的頭文件,以明確其中可用的方法。
我的問題是我有以下幾點:
// toolkit.cxx
#include "cache.h"
// Can't define operator()() here since it needs access the to cache instance
struct Functor {
void operator() ();
};
// Define Cache's fucntions here (including use of Functor)
namespace {
Cache cache;
// This gives a compiler error - definition of operator Functor::()() is not in namespace enclosing 'Functor'
void Functor::operator() () {
cache.refresh();
}
}
所以我不能在未命名的命名空間中定義Functor::operator()()
,它也不能在外面。
我考慮過的一種解決方案是將全部內容引入未命名的名稱空間,但這也必須包括#include
。 這是推薦的嗎? 這不是我以前真正看過的事情(這表明這可能是一個糟糕的計划...),而且我找不到關於這種方法的利弊的太多信息。
這個解決方案看起來像:
// toolkit.cxx
namespace {
#include "cache.h"
Cache cache;
struct Functor {
void operator()() {
cache.refresh();
};
// Define Cache's fucntions here (including use of Functor)
}
任何人都可以評論第二種方法的利弊嗎? 任何替代解決方案也將受到歡迎
解決方案1
在匿名namespace
定義Functor
。
#include "cache.h"
namespace {
Cache cache;
struct Functor {
void operator() () {
cache.refresh();
}
};
}
解決方案2
在定義匿名namespace
之后定義Functor
。
#include "cache.h"
namespace {
Cache cache;
}
struct Functor {
void operator() () {
cache.refresh();
}
};
解決方案3
聲明Functor
匿名之前namespace
,但是可以定義Functor::operator()
匿名的定義后namespace
。
#include "cache.h"
struct Functor {
void operator() ();
};
namespace {
Cache cache;
}
void Functor::operator() () {
cache.refresh();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.