【发布时间】:2016-06-04 23:13:34
【问题描述】:
我需要将模板作为函数参数传递,但模板必须接受所有继承的对象。
例如:
template <class T>
class Template {
public:
Template() {}
};
// IMPORTANT: must accept all children of "Base"
class Test {
Template<Base> *pointer;
public:
Test(Template<Base> *pointer) {...}
};
main() {
Template<Base> *base = new Template<Base>();
Template<Child1> *child = new Template<Child1>();
Test *test1 = new Test(base); // WORKING
// NEXT LINE IS IMPORTANT:
Test *test2 = new Test(child); // ERROR: no matching function for call to 'Test::Test(Template<Child1>*&)'
}
class Base {...};
class Child1 : public Base {...};
class Child2 : public Base {...};
..
我需要最有效的方法,如何将模板存储在“测试”类中,它将接受所有子类。我有很多儿童班。
1) 是否可以在参数中为 Child 类进行一些强制转换(static_cast)?在“模板”或“测试”类中使用它会很好。不是,在创建新的“测试”对象时,因为会有很多新对象。
2) 或者传递不带模板参数的参数Test(Template *pointer) {...}?
或者如何解决?
【问题讨论】:
-
Template<Child1>与Template<Base>完全无关。他们是完全不同的班级。根据您要执行的操作,类型擦除可能是一个可行的选择。 -
有什么阻止您将基类(非模板化)添加到 Template
并将其存储在您的测试类中吗? -
@coyotte508:是的,可以接受的解决方案,但我想知道,是否有模板参数继承的直接解决方案。
-
@Cornstalks:谢谢,会尝试类型擦除
标签: c++ templates inheritance parameters parameter-passing