Path: csiph.com!news.swapon.de!eternal-september.org!feeder2.eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail From: Ben Bacarisse Newsgroups: comp.lang.c++ Subject: Re: What's decltype doing here? Date: Tue, 07 Nov 2023 15:16:42 +0000 Organization: A noiseless patient Spider Lines: 55 Message-ID: <87wmut386d.fsf@bsb.me.uk> References: <878r7950vy.fsf@bsb.me.uk> MIME-Version: 1.0 Content-Type: text/plain Injection-Info: dont-email.me; posting-host="23ad4efdd42c9af5ecb199cc9f2cf504"; logging-data="1123576"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX19y2XmRw4Q6sRpWTYaaWG4+QvysiYSDiMM=" User-Agent: Gnus/5.13 (Gnus v5.13) Cancel-Lock: sha1:NUBZ84dkPGx0+Ti4ZfY3IMzygdQ= sha1:W9OAAdDVp/BwP3htDunGGEYsjWs= X-BSB-Auth: 1.b329c4014615ea4b18a3.20231107151642GMT.87wmut386d.fsf@bsb.me.uk Xref: csiph.com comp.lang.c++:117646 Bo Persson writes: > On 2023-11-07 at 11:11, Ben Bacarisse wrote: >> This question got a bit lost in another thread, so I am re-posting it on >> its own. What is decltype doing in the following short program? >> #include >> #include >> int main() >> { >> int x = 42; >> std::unique_ptr> std::cout << "delete (" << *p << ")\n"; >> })> upi(&x); >> } >> I expected decltype to supply just a type in the template and for a >> second argument to be required when constructing upi, but no. The >> program compiles (gcc and clang) and prints "delete (42)". >> The equivalent using a named function works as I expect: >> #include >> #include >> void deleter(int *p) { std::cout << "deleter (" << *p << ")\n"; }; >> int main() >> { >> int x = 42; >> std::unique_ptr upi(&x, deleter); >> } >> In this case it's an error to omit the second argument to the >> constructor. (I used decltype just to make the comparison clear but of >> course one could simply write the type (void (*)(int *)) in the template >> instead.) >> I am pretty sure that the answer is in some way related to the fact that >> C++ lambdas have unique types, but it's not clear to me what's really >> going on. Explanations welcome. Pointers to explanatory text in the >> standard even more so. > > You *have* the explanation right there. :-) > > The lambda has a unique type and can be default constructed, so that is > what happens. Ah. OK. It seems a little mysterious, but it's obvious when you see it. Here's a more direct example: #include int main() { decltype([](int i){std::cout << "i=" << i << "\n";}) f; f(42); } Thank you. -- Ben.