mixin template
vit
vit at vit.vit
Mon May 23 15:48:26 UTC 2022
On Monday, 23 May 2022 at 15:14:53 UTC, Vindex wrote:
> I have this code:
>
> ```
> import std.array, std.exception, std.stdio;
>
> mixin template RealizeException() {
> this(string msg, string file = __FILE__, size_t line =
> __LINE__) {
> super(msg, file, line);
> }
> }
>
> class WrongUsage : Exception {
> mixin RealizeException;
>
> this(string[] messages, string file = __FILE__, size_t line
> = __LINE__) {
> auto msg = std.array.join(messages, "\n");
> super(msg, file, line);
> }
> }
>
> void main() {
> throw new WrongUsage("Error message.");
> }
> ```
>
> ... and this error:
>
> ```
> mixin_exception.d(19): Error: constructor
> `mixin_exception.WrongUsage.this(string[] messages, string file
> = __FILE__, ulong line = cast(ulong)__LINE__)` is not callable
> using argument types `(string)`
> mixin_exception.d(19): cannot pass argument `"Error
> message."` of type `string` to parameter `string[] messages`
> Failed: ["/usr/bin/dmd", "-v", "-o-", "mixin_exception.d",
> "-I."]
>
> ```
>
> Why? Why can't I have two constructors when I use mixin?
>
> If I replace mixin to real code, I have no problem:
>
> ```
> class WrongUsage : Exception {
> this(string msg, string file = __FILE__, size_t line =
> __LINE__) {
> super(msg, file, line);
> }
>
> this(string[] messages, string file = __FILE__, size_t line
> = __LINE__) {
> auto msg = std.array.join(messages, "\n");
> super(msg, file, line);
> }
> }
> ```
mixin template create scope, for example if it was normal
function (no ctor), you can do this:
```d
mixin template RealizeException() {
static void foo(string){}
}
class WrongUsage{
mixin RealizeException x;
alias foo = x.foo;
static void foo(string[]){}
}
void main() {
WrongUsage.foo("Error message.");
}
```
But for ctor this doesn't work...
More information about the Digitalmars-d-learn
mailing list