简体   繁体   English

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

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

I'd like to have a type trait where I associate a class that implements an interface class with the interface class.我想要一个类型特征,我将实现接口 class 的 class 与接口 class 相关联。 For example, consider there is an abstract base class and a concrete implementation例如,考虑有一个抽象基 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
};

Now, I am looking for a way to use a type trait to get a type that's a concrete implementation of IFoo so that the following would be possible:现在,我正在寻找一种使用类型特征来获取作为IFoo的具体实现的类型的方法,以便可以进行以下操作:

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

Does anyone know if this is possible with C++ type traits?有谁知道 C++ 类型特征是否可能?

There is no standard way to do it.没有标准的方法来做到这一点。 If there're many subclasses extends from the special class, which one should be returned?如果从特殊的 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;
}

It's necessary to register implementation class by some means.有必要通过某种方式注册实现 class。 There's a simple way:有一个简单的方法:

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();
}

so you can:这样你就可以:

// 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