template Test(this ThisType) { pragma(msg, ThisType); } void main() { alias T = Test!int; // Prints "int" } This will also work for class templates, struct templates, alias templates, enum templates, etc., but not for templated methods. It doesn't matter if the template is a free template or nested within a struct or class.
What's the advantage over a normal template type parameter?
import std.stdio; class Base { void test1(T = typeof(this))() { writeln("test1: ", T.stringof); } void test2(this T)() { writeln("test2: ", T.stringof); } } class Derived: Base { } void main() { new Base().test1(); //test1: Base new Base().test2(); //test2: Base new Derived().test1(); //test1: Base new Derived().test2(); //test1: Derived }
Isn't comment 2 what we have already? The title says 'allow any type to be passed' and the example uses int.
> Isn't comment 2 what we have already? Ya, I created this issue because any template allows you to use the `this T` syntax, and it will accept any type (which seemed like a bug at the time). I still think it's confusing, and it does nothing in a template that's not nested in an aggregate, but might not necessarily be behaviour that needs to be fixed.
Oh I see, it should only be allowed for methods.
@ntrel created dlang/dmd pull request #14434 "Fix Issue 13732 - non-member templates can use "template this"" fixing this issue: - Fix Issue 13732 - non-member templates can use "template this" https://github.com/dlang/dmd/pull/14434
@ntrel created dlang/dmd pull request #14447 "Fix Issue 13732 - non-member templates can use "template this"" fixing this issue: - Fix Issue 13732 - non-member templates can use "template this" Error if a TemplateThisParameter is declared where `typeof(this)` would be an error. Error if a TemplateThisParameter is passed a type that doesn't convert to `const typeof(this)`. Note: This is done with a dummy specialization, which causes the correct semantic error messages even for mixin and may be more efficient than checking this in dtemplate.d. https://github.com/dlang/dmd/pull/14447
dlang/dmd pull request #14434 "Fix Issue 13732 - non-member templates can use "template this"" was merged into master: - c22f40bb47b98a0a18ffca0a6766047e81784d35 by Nick Treleaven: Fix Issue 13732 - non-member templates can use "template this" https://github.com/dlang/dmd/pull/14434