作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我有很多类 A、B、C、D 等,它们都是鸭子类型的,因此具有相同的方法和接口(interface),但不是从同一个类继承的。
例如
class A {
public:
void foo();
void bar();
}
class B {
public:
void foo();
void bar();
}
class C {
public:
void foo();
void bar();
}
我想在运行时将 const char *
映射到这些类之一的相应实例,例如
“A”
-> A a
“B”
-> B b
这里 a
是类 A
的一些实例。
或在编译时将 'const char *` 映射到相应的类型,例如
“A”
-> A
我需要在其他一些函数调用中使用该对象的实例(即调用 foo()
或 bar()
),但 API 只能接受一个const char * 作为底层对象被抽象掉。
我在一个大型代码生成的代码库中工作,因此改变范式是不切实际的。
最佳答案
使用适配器接口(interface)和一堆实现该接口(interface)的具体适配器执行类型删除;适配器可以是类模板的实例。
struct IFooBar {
virtual ~IFooBar() {}
virtual void foo() = 0;
virtual void bar() = 0;
};
template<class T> struct FooBarAdaptor : IFooBar {
T* t;
FooBarAdaptor(T* t) : t{t} {} ~FooBarAdaptor() {}
void foo() override { return t->foo(); }
void bar() override { return t->bar(); }
};
// ...
A a;
B b;
C c;
std::map<std::string, std::unique_ptr<IFooBar>> m;
m["a"] = std::make_unique<FooBarAdaptor<A>>(&a);
m["b"] = std::make_unique<FooBarAdaptor<B>>(&b);
m["c"] = std::make_unique<FooBarAdaptor<C>>(&c);
关于c++ - 在编译时或运行时将 const char * 映射到 duck-typed T,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30876005/
我是一名优秀的程序员,十分优秀!