Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
636 views
in Technique[技术] by (71.8m points)

reflection - Is it possible to detect namespace membership in C++?

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!     
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...