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
181 views
in Technique[技术] by (71.8m points)

c++ - Argument dependent name lookup and typedef

I would not have expected this code to compile, but it does. My understanding is that func(d) it looks in the global namespace for a function called "func" but also in the namespace of any passed in parameters (Argument dependent lookup)

But in this case the parameter is in the global namespace. So why does it find "func" in the ns namespace? Are there special rules saying that if the parameter type is a typedef then it uses the namespace of the underlying type rather than the namespace of the actual parameter?

This appears to be true but I can't find anything supporting this... Is it the expected behavour?

namespace ns
{
    struct data {};
    void func(ns::data item) {}
};

// Create an alias "datatype" in the global namespace for ns::data
typedef ns::data datatype;


int main()
{
    datatype d;
    func(d);
}
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

The parameter d is local to main. datatype is just an alias for the type ns::data so d has type ns::data.

ns::data is a [direct] member of the ns namespace so this functions in the ns namespace will be considered for ADL.


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

...