Is it possible to detect namespace membership in C

2020-02-12 10:26发布

问题:

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.

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).

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.

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: as pointed out by K-ballo, a namespace cannot be used as a template parameter so a type-trait seems impossible.

EDIT2: here's the skeleton as hinted to by K-ballo: what nifty test can (or cannot?) be cooked up there?

#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!     

回答1:

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.