I'd like to have a type trait where I associate a class that implements an interface class with the interface class. For example, consider there is an abstract base class and a concrete implementation
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:
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?
There is no standard way to do it. If there're many subclasses extends from the special class, which one should be returned?
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. 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>();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.