![](/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.