C++ Logo

sg20

Advanced search

Re: namespace composition

From: Ville Voutilainen <ville.voutilainen_at_[hidden]>
Date: Sat, 29 Apr 2023 01:11:00 +0300
On Fri, 28 Apr 2023 at 22:12, Bjarne Stroustrup via SG20
<sg20_at_[hidden]> wrote:
>
> This question is in the context of teaching novices. For experienced
> programmers, I have workarounds.
>
> I would like to make all of the standard library available
>
> as a module based on module std
>
> with guaranteed range checking
>
> without requiring students to write std:: all the time
>
> and add a few supporting features
>
> I have successfully done that for tens of thousands of students over
> more than a decade using some disgusting macro tricks. Think
>
> #define vector My_checked_vector
>
> Having guaranteed range checking is a great help to students. I estimate
> that it eliminates more than 50% of crashes and lots of frustration.
>
> Modules and disgusting macro tricks don't go well together
>
> I was planning to use
>
> using vector = My_checked_vector
>
> but I can't find a way for that to work together with
>
> using namespace std;
>
> Am I being blind?
>
> Any suggestions?
>
> I can get away with a single #using "PPP_support.h" containing three
> macros, but I would really like to avoid that.
>
> I suspect the fundamental problem is that there is no way of composing a
> module or a namespace saying "I want all of Foo, except that I want my
> own versions of Foo::X and Foo:Y." I would *love* to be proven wrong
> about that. The original namespace design had such a mechanism, but I
> have not been able to get it to work.

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.

We could of course entertain a language facility that allows doing "do
a using-declaration for every member of namespace X, except this and
that".
Sounds like a reflection+injection use case to me.

Received on 2023-04-28 22:11:13