繁体   English   中英

如何将类型添加为类型特征

[英]How to add a type as a type trait

我想要一个类型特征,我将实现接口 class 的 class 与接口 class 相关联。 例如,考虑有一个抽象基 class 和一个具体实现

class IFoo
{
public:
    virtual ~IFoo() = default;
    virtual void doStuff() = 0;
    // more abstract base class stuff
};
class ConcreteFoo: public IFoo
{
public:
    void doStuff() override;
    // concrete class stuff
};

现在,我正在寻找一种使用类型特征来获取作为IFoo的具体实现的类型的方法,以便可以进行以下操作:

using IFooImpl = get_implementation_of<IFoo>::type;
std::unique_ptr<IFoo> foo = std::make_unique<IFooImpl>();

有谁知道 C++ 类型特征是否可能?

没有标准的方法来做到这一点。 如果从特殊的 class 扩展而来的子类很多,应该返回哪一个?

class task {
public:
  
  virtual void execute() = 0;
};

class hello_world_task : 
  public virtual task {
public:
  
  virtual void execute() override {

    std::cout << "Hello World!" << std::endl;
  }
};

class exit_task : 
  public virtual task {
public:

  virtual void execute() override {

    std::exit(0);
  }
};

auto fun() {

  // `exit_task` or `hello_world_task` ?
  using task_impl = get_implementation_of<task>::type;
}

有必要通过某种方式注册实现 class。 有一个简单的方法:

template <typename T>
struct get_implementation_of {
};

template <>
struct get_implementation_of<task> {
  using type = hello_world_task;
};

auto fun() {

  // task is hello_world_task
  using task_impl = get_implementation_of<task>::type;
  task_impl().execute();
}

这样你就可以:

// register ConcreteFoo as the implementation class of IFoo
template <>
struct get_implementation_of<IFoo> {
  using type = ConcreteFoo;
};

auto fun() {

  using IFooImpl = get_implementation_of<IFoo>::type;
  std::unique_ptr<IFoo> foo = std::make_unique<IFooImpl>();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM