C++ Logo

sg20

Advanced search

Re: [isocpp-ext] namespace composition

From: Andrew Tomazos <andrewtomazos_at_[hidden]>
Date: Sat, 29 Apr 2023 07:58:14 +1000
On Sat, Apr 29, 2023 at 5:12 AM Bjarne Stroustrup via Ext <
ext_at_[hidden]> wrote:

> 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.
>

Bjarne,

GPT-4 responds as follows to your question. (Please tell me if it got it
right. Thanks -Andrew)

GPT-4: I understand your predicament. You want to make the standard
library available with range checking for your students while avoiding the
use of macros and minimizing the need for them to use the `std::` prefix.

Unfortunately, there is no direct way to achieve your goal with the
combination of C++ modules and namespaces without using macros. However,
there is an alternative that might be helpful.

You can create a new namespace, let's call it `student`, which includes all
the standard library components and your custom range-checked components.
Then, ask your students to use the `student` namespace.

Here's a step-by-step process:

1. Create a header file, for example, `student_std.hpp`:

```cpp
#pragma once

#include <vector>
#include <iostream>
// ... include other standard library components

#include "My_checked_vector.hpp" // Include your custom range-checked vector

namespace student {
    // Import all standard library components into the student namespace
    using namespace std;

    // Use your custom range-checked vector as a replacement for std::vector
    using vector = My_checked_vector;

    // Add other custom components, if needed
}
```

2. Ask your students to include this header file in their code and use the
`student` namespace:

```cpp
#include "student_std.hpp"

using namespace student;

int main() {
    vector<int> v = {1, 2, 3};

    // Accessing elements with range checking
    int x = v.at(0);
    cout << x << endl;

    return 0;
}
```

This way, you provide your students with a namespace that includes all the
standard library components along with your custom range-checked vector.
This solution doesn't rely on macros, and it's compatible with modules.

As for your question regarding composing a module or namespace to exclude
specific components, there is no direct mechanism in C++ to achieve that.
The closest solution would be the one mentioned above.

Please note that my knowledge is up to date only until September 2021, and
I may not have information on recent developments or events.

Received on 2023-04-28 21:58:27