C++ Logo

sg20

Advanced search

Re: namespace composition

From: Ville Voutilainen <ville.voutilainen_at_[hidden]>
Date: Sat, 29 Apr 2023 01:19:37 +0300
On Sat, 29 Apr 2023 at 01:11, Ville Voutilainen
<ville.voutilainen_at_[hidden]> wrote:
> We can actually do such composition, but..
> https://wandbox.org/permlink/8Av08StRKKBvAzgW
> Pasted here for convenience:
>
> #include <string>
> #include <iostream>
> #include <vector>
>
> namespace PPP {
> using namespace std;
> struct vector {void found_our_own() {}};
> }
>
> int main() {
> PPP::string s;
> PPP::vector v;
> v.found_our_own();
> }
>
> So, we can compose things in such a manner that when using qualified
> names, i.e. PPP::vector, that works - PPP::string is std::string,
> PPP::vector is the vector I defined. Unambiguously.
>
> But you can't do a using namespace PPP in main(), and then use string
> and vector unqualified. In that case vector becomes an ambiguous
> type.

And yes, the most-likely-incorrect chatbot got it right too, you can also do

namespace gollywogs {
    struct vector {void found_our_own() {}};
}
namespace PPP {
    using namespace std;
    using gollywogs::vector;
}

int main() {
    PPP::string s;
    PPP::vector v;
    v.found_our_own();
}

and that works fine. All current answers require a namespace to be
used, and you can't get rid of it
with a using-directive, because that stops this technique from working.

Received on 2023-04-28 22:19:50