是否可以检测C ++中的命名空间成员资格? [英] Is it possible to detect namespace membership in C++?
问题描述
对于C ++类型,< type_traits>
头给我们提供了许多有用的编译时反射能力。例如。 std :: is_base_of< B,D> :: value
在编译时确定 B
是否是 D
。
For C++ types, the <type_traits>
header gives us many useful compile-time reflection capabilities. E.g. std::is_base_of<B, D>::value
determines at compile-time whether B
is a base class of D
.
我不知道是否可以检测类似行的命名空间成员资格?例如。给定具有类型 T
的命名空间 N
是否有一种方法来确定 T
使用 IS_NAMESPACE_MEMBER_OF(T,N)
形式的宏表达式包含在 N
I wonder if it would be possible to detect namespace membership along similar lines? E.g. given a namespace N
with a type T
, is there a way to determine whether T
is contained within N
using a macro expression of the form IS_NAMESPACE_MEMBER_OF(T,N)
.
我喜欢通过任何类型的SFINAE / ADL类型的骗子的编译时答案。或者,如果不可能,某种推理为什么标准将不允许这样。
I'd prefer a compile-time answer through any sort of SFINAE / ADL type of trick. Or, if it isn't possible, some sort of reasoning why the Standard would not allow this.
非便携式和运行时黑客将是regex typeid(T).name()
N
,但这是相当乏味的,而不是在编译时。
A non-portable and run-time hack would be to regex typeid(T).name()
for N
, but this is rather tedious and not at compile-time.
EDIT1 :如K-ballo所指出的,命名空间不能用作模板参数,所以类型trait似乎是不可能的。
EDIT1: as pointed out by K-ballo, a namespace cannot be used as a template parameter so a type-trait seems impossible.
EDIT2 :
#define IS_NAMESPACE_MEMBER_OF(T, N) \
\
// global declaration \
void test(T); \
\
// namespace declaration \
namespace N { \
void test(T); \
} \
\
// some clever name lookup / sizeof / SFINAE test!
推荐答案
命名空间不是有效的模板参数,永远不会是一个阶级的特质。也许你可以做一些东西晦涩的宏。你可以在测试命名空间中注入函数,并使用ADL和 sizeof
/ decltype
挑选。
A namespace is not a valid template parameter, so it could never be a class trait. Perhaps you can do something obscure with macros though. You could maybe inject functions in the test namespace and use ADL together with a sizeof
/decltype
trick to see which overload gets picked.
这篇关于是否可以检测C ++中的命名空间成员资格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!