【发布时间】:2021-09-26 22:02:56
【问题描述】:
我有两个模板类Derived1 和Derived2 都派生自Base。
我希望foo 可以通过模板实例化返回Derived1 或Derived2,并且它们的类型由参数use_int 区分。
class Base {
public:
virtual ~Base() = default;
};
template <typename T>
class Derived1 : public Base {};
template <typename T>
class Derived2 : public Base {};
template <typename Derived>
Base *foo(bool use_int) {
if (use_int)
return new Derived<int>();
else
return new Derived<float>();
}
int main() {
Base *obj1 = foo<Derived1>(true);
Base *obj2 = foo<Derived2>(false);
delete obj1;
delete obj2;
return 0;
}
但它不会编译。
t.cc: In function ‘Base* foo(bool)’:
t.cc:12:16: error: ‘Derived’ is not a template
12 | return new Derived<int>();
| ^~~~~~~
t.cc:14:16: error: ‘Derived’ is not a template
14 | return new Derived<float>();
| ^~~~~~~
t.cc: In function ‘int main()’:
t.cc:18:34: error: no matching function for call to ‘foo<template<class T> class Derived1>(bool)’
18 | Base* obj1 = foo<Derived1>(true);
| ^
t.cc:10:7: note: candidate: ‘template<class Derived> Base* foo(bool)’
10 | Base* foo(bool use_int) {
| ^~~
t.cc:10:7: note: template argument deduction/substitution failed:
t.cc:19:35: error: no matching function for call to ‘foo<template<class T> class Derived2>(bool)’
19 | Base* obj2 = foo<Derived2>(false);
| ^
t.cc:10:7: note: candidate: ‘template<class Derived> Base* foo(bool)’
10 | Base* foo(bool use_int) {
| ^~~
t.cc:10:7: note: template argument deduction/substitution failed:
这是因为Derived1 或Derived2 不是完整类型吗?我该如何解决这个问题?
【问题讨论】: