gpt4 book ai didi

c++ - 模板实例化抽象基类的子类的构造函数 - 需要替代设计模式

转载 作者:行者123 更新时间:2023-11-28 03:15:05 25 4
gpt4 key购买 nike

我有一个这样的模板:

template<typename T>
struct foo {
foo(T t) {
//code
}
virtual double computation() = 0;
//other members
};

我希望用户为他们自己的子类提供自定义 Tcomputation(),如下所示:

struct my_foo : public foo<std::string> {
double computation() override { return 9.99; }
};

问题是这不起作用:

my_foo("hello");

我将不得不要求用户为每个子类创建一个新的构造函数,即使它所做的只是调用父类(super class)构造函数。这看起来很傻。

你能推荐更适合我的替代“设计模式”吗?

最佳答案

我认为它与模板没有直接关系。

仅仅是因为:在C++中,构造函数是不被继承的。

试试这个例子,你会发现它不起作用:

class Parent {
public:
Parent(int i) {
cout << "i " << i << endl;
};
};

class Child : public Parent {
};

int main(int argc, char** args) {
Child child(1);
return 0;
}

因为默认情况下,Child 的构造函数将调用 Parent 的无参数构造函数。然而,no-arg ctor 在 Parent 中不可用。

更改 Child 以提供适当的 ctor 将解决问题:

class Child : public Parent {
public:
Child(int i):Parent(i) {
}
};

在这个例子中,我为 Child 创建了一个构造函数,它接受 1 个参数。此子构造函数将调用父构造函数的 Parent(int) 构造函数。

在您的问题中,您说要求子类创建构造函数很愚蠢:一点也不愚蠢!你永远不会知道 child 希望它的类如何被实例化。某些子类可能只根据其语义含义为ctor构造2个参数是合理的。

如果您真的真的希望神奇地完成它,您可以做的一种最简单的方法是创建宏来为子类“生成”类声明和相应的构造函数。然而,这样做几乎没有意义。

关于c++ - 模板实例化抽象基类的子类的构造函数 - 需要替代设计模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17158281/

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