Le mercredi 06 avril 2016 à 06:48 -0700, Daniel Arndt a écrit :
> This is shorter than it looks, it's mostly code / output. Feel free
> to skip to the tl;dr.
>
> I'm playing around with an idea where I've created a new type that
> wraps an IOBuffer.
>
> This new type would hold some other information as well, but for it's
> read/write operations, I wanted to just pass the calls on to the
> encapsulated IOBuffer. I thought this would be fairly simple (as any
> good programming story begins):
>
> import Base: write
>
>
> type NewIOType <: IO
> buffer::IOBuffer
> some_other_stuff::Int
>
> new() = new(IOBuffer())
> end
>
>
> write(io::NewIOType, x...) = write(io.buffer, x...)
>
> However, write seems to conflict with multiple other definitions:
>
> WARNING: New definition
> write(Main.NewIOType, Any...) at In[1]:10
> is ambiguous with:
> write(Base.IO, Base.Complex) at complex.jl:78.
> To fix, define
> write(Main.NewIOType, Base.Complex)
> before the new definition.
> WARNING: New definition
> write(Main.NewIOType, Any...) at In[1]:10
> is ambiguous with:
> write(Base.IO, Base.Rational) at rational.jl:66.
> ...
> and on and on
> ...
>
> I understand the problem: Although my first parameter is more
> specific, my second is not. In an exploratory move, I tried:
>
> write{T}(io::NewIOType, x::T) = write(io.buffer, x)
>
> Thinking that this would create a new write function for every type T
> and therefore be more specific (I could use some clarity here, as
> obviously my understanding is incorrect). I get this:
>
> WARNING: New definition
> write(Main.NewIOType, #T<:Any) at In[1]:10
> is ambiguous with:
> write(Base.IO, Base.Complex) at complex.jl:78.
> To fix, define
> write(Main.NewIOType, _<:Base.Complex)
> before the new definition.
> WARNING: New definition
> write(Main.NewIOType, #T<:Any) at In[1]:10
> is ambiguous with:
> write(Base.IO, Base.Rational) at rational.jl:66.
> To fix, define
> write(Main.NewIOType, _<:Base.Rational)
>
> tl;dr Can I wrap an IO instance, and pass all calls to 'write' to the
> wrapped instance's version?
>
> I am entirely capable and aware of other approaches, so while I do
> appreciate suggestions of alternative approaches, I am specifically
> wondering if there is some mechanism that I'm missing that easily
> overcomes this.
I think you only need to provide write(s::NewIOType, x::UInt8). All
higher-level write() methods will automatically use it.
Regards