【问题标题】:Can I refer to the template's base class?我可以参考模板的基类吗?
【发布时间】:2020-06-08 10:49:06
【问题描述】:

有没有办法引用当前提供的模板的基类?例如,

template <class UserType>
class User
{
    public:
        User()
        {
            user_manager_ = std::make_unique<UserType>();
        }

   private:
        std::unique_ptr<UserType::Base> user_manager_; // <-- I want this ptr to be the type of base of UserType i.e. IUserManager
}

【问题讨论】:

  • C++ 没有反射。您可以提出自己的要求,即与此模板一起使用的每个类都必须定义一个内部 Base 类型。就像 C++ 库中的所有容器都定义了value_typeiterator 等...
  • 除非UserType 确实定义了Base 类型,否则这是不可能的。考虑到 C++ 允许多重继承,获得单个基类的可能性就更小了。如果UserType 继承自多个基,你会选择哪一个?
  • 另外,您需要解决的实际问题是什么?为什么需要指向基类的指针?从变量和类型的名称来看,为什么“用户”类会从“管理器”类继承? “用户不是“经理”(请记住,继承是一种“is-a”关系)。也许更好的选择是UserType 拥有一个返回指向“经理”对象的指针的函数?
  • 可能有多个基类,所以请记住这种边缘情况。此外,虽然没有直接回答您的问题,但如果您有一组要检查的基类,可以使用 en.cppreference.com/w/cpp/types/is_base_of
  • @Someprogrammerdude 你说的很有道理。关于名称,它们只是我想出的假设名称。实际问题不同。我想我想暗示“根据用户类型创建经理”,但这并不重要,因为这只是我写的假设。实际的一点是我希望指针是模板类的接口类型。您的解释是有道理的,为什么这是不可能的。谢谢。

标签: c++ templates inheritance


【解决方案1】:

不,因为 c++ 中的多重继承。做类似事情的唯一方法是:

struct A {};

struct UserType : public A {
  using Base = A;
};

template<class UserType>
class User {
 public:
  User() {
    user_manager_ = std::make_unique<UserType>();
  }

 private:
  std::unique_ptr<typename UserType::Base> user_manager_; // <-- I want this ptr to be the type of base of UserType i.e. IUserManager
};

【讨论】:

    猜你喜欢
    • 2014-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多