FYI: Be careful with imports when using public:

Jonathan M Davis newsgroup.d at jmdavisprog.com
Wed Oct 11 05:31:33 UTC 2023


On Tuesday, October 10, 2023 9:53:07 PM MDT Salih Dincer via Digitalmars-d 
wrote:
> On Tuesday, 10 October 2023 at 07:43:26 UTC, Jonathan M Davis
>
> wrote:
> > ... In this particular case, the confusing result is that
> > trying to call functions in std.range.primitives (such as
> > walkLength or moveFront) on an instance of Foo using UFCS will
> > result in the code not compiling (whereas using the normal
> > function call syntax works just fine), and the error messages
> > don't make it all clear as to why, so it took me quite a while
> > to figure out what the problem was.
>
> I didn't experience any compilation errors or import problems
> either. Moreover, I also tried selective import. For example:
>
>
> ```d
>
> --main.d--
> import publicCase;
>
> import std.stdio;
> void main() {
>    auto s = S(" No Problem ");
>    s.wordCount.writeln(": ", s);
>    // 2: S(" No Problem ")
> }
>
> --publicCase.d--
> module publicCase;
>
> struct S
> {
>    private:
>      string str;
>
>    public:
>     import std.range.primitives;// : walkLength;
>     import std.algorithm;// : splitter;
>
>    size_t length() => str.length;
>    size_t wordCount() => str.splitter.walkLength;
> }
> ```
>
> SDB at 79

The problem is not using the imports inside of the struct where you have the
public import (since whether imports are public or not has no impact on the
part of the code where they're imported, just on other modules importing
that code). The problem is using them on the struct from within another
module. So, if you have something like

a.d
---
struct Range
{
public:
    import std.range.primitives;

    int front() { return _i; }
    void popFront() { ++_i;}
    bool empty() { return _i == 10; }

private:
    int _i;
}

main.d
------
void main()
{
    import std.range.primitives;
    import a;
    auto l = Range.init.walkLength();
}

This will result in

main.d(5): Error: none of the overloads of template 
`std.range.primitives.walkLength` are callable using argument types `!()()`
/usr/local/include/dmd/std/range/primitives.d(1767):        Candidates are: 
`walkLength(Range)(Range range)`
/usr/local/include/dmd/std/range/primitives.d(1795):                        
`walkLength(Range)(Range range, const size_t upTo)`

- Jonathan M Davis





More information about the Digitalmars-d mailing list