gpt4 book ai didi

c++ - 在编译时或运行时将 const char * 映射到 duck-typed T

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:28:10 24 4
gpt4 key购买 nike

我有很多类 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com