digitalmars.D.learn - Is there a better way to do this? (Using class at compile-time)
- bauss (40/40) Jun 12 2018 Let's say I have something like the following:
- Simen =?UTF-8?B?S2rDpnLDpXM=?= (11/22) Jun 12 2018 [snip]
- bauss (4/28) Jun 12 2018 Thanks, that might work way better!
Let's say I have something like the following: abstract class Foo { abstract string baz(); abstract string helloworld(); } final class Bar(T) : Foo { override string baz() { return "writeln(\"Hello " ~ T.stringof ~ "!\");"; } override string helloworld() { return "writeln(\"Hello World!\");"; } } auto getBar(T)() { return new Bar!T; } void test(T)() { pragma(msg, (getBar!T).baz()); pragma(msg, (getBar!T).helloworld()); import std.stdio; mixin((getBar!T).baz()); mixin((getBar!T).helloworld()); } void main() { test!int; } Is there a way to avoid having to write "getBar!T" every time since we cannot store a class into a compile-time variable, how would one avoid such thing? The best I can think of is an alias like: void test(T)() { alias bar = getBar!T; pragma(msg, bar.baz()); pragma(msg, bar.helloworld()); import std.stdio; mixin(bar.baz()); mixin(bar.helloworld()); } But I'm positive there must be a better way.
Jun 12 2018
On Tuesday, 12 June 2018 at 11:04:40 UTC, bauss wrote: [snip]void test(T)() { pragma(msg, (getBar!T).baz()); pragma(msg, (getBar!T).helloworld()); import std.stdio; mixin((getBar!T).baz()); mixin((getBar!T).helloworld()); }[snip]Is there a way to avoid having to write "getBar!T" every time since we cannot store a class into a compile-time variable, how would one avoid such thing?static const instance = new Bar!T; enum text1 = b.baz(); enum text2 = b.helloworld(); However, since it's a const instance, you'll only be able to call const methods on it, and you'll need to mark baz and helloworld as const. -- Simen
Jun 12 2018
On Tuesday, 12 June 2018 at 11:18:00 UTC, Simen Kjærås wrote:On Tuesday, 12 June 2018 at 11:04:40 UTC, bauss wrote: [snip]Thanks, that might work way better! My situation is a little different than what my example showed, but I should be able to get it working with static const.void test(T)() { pragma(msg, (getBar!T).baz()); pragma(msg, (getBar!T).helloworld()); import std.stdio; mixin((getBar!T).baz()); mixin((getBar!T).helloworld()); }[snip]Is there a way to avoid having to write "getBar!T" every time since we cannot store a class into a compile-time variable, how would one avoid such thing?static const instance = new Bar!T; enum text1 = b.baz(); enum text2 = b.helloworld(); However, since it's a const instance, you'll only be able to call const methods on it, and you'll need to mark baz and helloworld as const. -- Simen
Jun 12 2018