Why does templated interface function return something different than final function?

Steven Schveighoffer schveiguy at gmail.com
Thu Aug 2 20:35:57 UTC 2018


On 7/18/18 7:09 AM, Timoses wrote:
> Why is the interface templated function not also returning the class C 
> toString return value "in C"??
> 
>      interface iface
>      {
>          void toString(scope void delegate(const(char)[]) sink) const;
> 
>          final string convert() inout
>          {
>              import std.conv;
>              // assert(std.conv.to!string(this) == "in C"); // fails!
>              return std.conv.to!string(this);
>          }
> 
>          final string convert2() const
>          {
>              import std.conv;
>              assert(std.conv.to!string(this) == "in C");
>              return std.conv.to!string(this);
>          }
>      }
> 
>      class C : iface
>      {
>          void toString(scope void delegate(const(char)[]) sink) const
>          {
>              sink("in C");
>          }
>      }
> 
>      void main ()
>      {
>          iface i = new C();
>          import std.stdio;
>          writeln(i.convert); // "app.C"
>          writeln(i.convert2()); // "in C"
>      }
> 
> It seems like `inout` triggers some odd behaviour??

Looking at the AST, it appears that toImpl doesn't recognize what 
inout(iface) is:

toImpl!(string, inout(iface))
{
	@system string toImpl(ref inout(iface) value)
	{
		import std.array : appender;
		import std.format : FormatSpec, formatValue;
		Appender!string w = appender();
		FormatSpec!char f = FormatSpec;
		formatValue(w, value, f);
		return w.data();
	}

}

Vs. the nice neat call for const(iface)

toImpl!(string, const(iface))
{
	@system string toImpl(const(iface) value)
	{
		return toStr(value);
	}

}

Note the ref there, too. This means it can't cast to const. I wonder if 
that's an issue.

-Steve


More information about the Digitalmars-d-learn mailing list