gpt4 book ai didi

templates - 为什么这些模板化函数的行为不像虚函数?

转载 作者:行者123 更新时间:2023-12-04 06:02:46 26 4
gpt4 key购买 nike

在下面的代码中,我希望输出是

B
C

但令人沮丧的是
A
C

有什么我可以做的让它按照我期望的方式运行吗?为什么首先会发生这种行为?
我已经让自己定义了 stuff 的 mixin 模板并将其混合到覆盖 write 的每个类中,这解决了问题,但 IMO 是一个丑陋的黑客。
import std.stdio : writeln;

class A {
void write() {
stuff();
}

void stuff()() {
writeln("A");
}
}


class B : A {
void stuff()() {
writeln("B");
}
}

class C : A {
void write() {
stuff();
}

void stuff()() {
writeln("C");
}

}

void main (string[] args) {
B b = new B();
b.write();
C c = new C();
c.write();
}

最佳答案

引用 online documentation ,

Tem­plates can­not be used to add non-sta­tic mem­bers or vir­tual func­tions to classes.

关于templates - 为什么这些模板化函数的行为不像虚函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8752702/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com