【问题标题】:C++ return different derived template class based on runtime argumentC++ 根据运行时参数返回不同的派生模板类
【发布时间】: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 不是完整类型吗?我该如何解决这个问题?

【问题讨论】:

    标签: c++ class templates


    【解决方案1】:

    Derived1 和 Derived2 是模板。如果要将它们用作模板参数,则应将 Derived 声明为 template template parameter。例如

    template <template <typename> typename Derived>
    Base* foo(bool use_int) {
      if (use_int)
        return new Derived<int>();
      else
        return new Derived<float>();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-06-22
      • 1970-01-01
      • 1970-01-01
      • 2013-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多