[英]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.