gpt4 book ai didi

c++ - 异构指针容器

转载 作者:行者123 更新时间:2023-11-30 04:34:31 25 4
gpt4 key购买 nike

我目前正在使用枚举映射到 Base* 数组。每个派生类型都由枚举指定一个索引。

enum DerivedType {
DERIVED_TYPE_1 = 0,
DERIVED_TYPE_2,
...
NUM_DERIVED_TYPES
};


class Base {

};


class Derived1 : public Base {
static const DerivedType type;
};
const DerivedType Derived1::type = DERIVED_TYPE_1;


class Derived2 : public Base {
static const DerivedType type;
};
const DerivedType Derived2::type = DERIVED_TYPE_2;


class Container {
Base* obs[NUM_DERIVED_TYPES];

template<class T>
void addOb(T* ob) {
obs[T::type] = ob;
}

template<class T>
T* getOb() {
return (T*) obs[T::type];
}

Base* getOb(DerivedType type) {
return obs[type];
}
};

由于每个派生类型的索引在编译时都是已知的,有没有办法让非模板 getOb(DerivedType type) 返回正确的 DerivedN 指针,也许通过查找类型名在 int -> typename 映射中?或者有没有更好的方法来实现这种模式?此外,最好让每个 Derived 类型都将自身添加到为其分配索引值的任何数据结构中。

基本上,我需要一个可以按类型或按索引访问的静态异构指针容器,同时始终返回正确的 Derived*。我猜 Boost 有一些有用的东西,但我还没有找到它。

感谢您的帮助。

最佳答案

虽然我不能 100% 确信我正确理解了问题,可能你提到的(或类似的)可以实现使用 boost::fusionboost::mpl
例如:

#include <boost/fusion/include/map.hpp>
#include <boost/fusion/include/at_key.hpp>
#include <boost/mpl/vector.hpp>
namespace bf = boost::fusion;
namespace bm = boost::mpl;

// This order has to match with the enumerators in DerivedType
typedef bm::vector< Derived1, Derived2 > DerivedTypes;

typedef bf::map< bf::pair< Derived1, Derived1* >
, bf::pair< Derived2, Derived2* > > Container;

int main() {
Container c( bf::make_pair< Derived1, Derived1* >(0)
, bf::make_pair< Derived2, Derived2* >(0) );
Derived1 d1;
Derived2 d2;
bf::at_key< Derived1 >( c ) = &d1; // access with type
bf::at_key< Derived2 >( c ) = &d2;
// access with enum
bf::at_key< bm::at_c< DerivedTypes, DERIVED_TYPE_1 >::type >( c ) = &d1;
bf::at_key< bm::at_c< DerivedTypes, DERIVED_TYPE_2 >::type >( c ) = &d2;
}

关于c++ - 异构指针容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5932079/

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