我有一个通过继承定义的 C++ 类层次结构,并在其中存储了该层次结构的描述,以便稍后用于内省(introspection)。我想知道是否有比我目前的方式更有效或更清晰的方法来定义它。 这是我的代码的精简版本
// in header file (hpp)
struct Type
{
Type( const string& n, const Type* p = nullptr ) : name(n), parent(p) {}
const string name;
const Type* parent;
};
class Base
{
public:
static const Type m_type;
virtual const Type& type() const { return m_type; }
};
class Derived : public Base
{
public:
static const Type m_type;
const Type& type() const { return m_type; }
};
// in implementation file (cpp)
const Type Base::m_type( "Base" );
const Type Derived::m_type( "Derived", &Base::m_type );
最佳答案
不一定更高效,但请考虑您是否确实需要一个公共(public)基类。另一种方法使用全局类型信息注册表。然后通过 TypeInfo::get(my_variable)
或 TypeInfo::get(typeid(my_type))
查询类型的类型信息。
这样做的优点是它也适用于现有类型,只需将其添加到此类型信息注册表中即可。
在内部,注册表将使用从 std::type_info
到 Type
或类似的映射。以下是概念证明。不幸的是,该代码无法在 clang 或 GCC 上编译。根据错误消息,我怀疑存在错误,但也可能是错的......
struct Type {
std::string name;
std::vector<Type*> parents;
// TODO Extend by fully-qualified name (namespace) etc.
template <typename... T>
Type(std::string&& name, T*... parents)
: name(name), parents{parents...} { }
};
struct TypeInfo {
template <typename T>
static Type const& get(T const&) { return get(typeid(T)); }
template <typename T>
static Type const& get() { return get(typeid(T)); }
static Type const& get(std::type_info const& info) {
auto i = types.find(info);
if (i == types.end())
throw unknown_type_error(info.name());
return i->second;
}
template <typename T>
static void register_type(Type&& type) {
types.insert(std::make_pair(typeid(T), type));
}
typedef std::unordered_map<std::type_info, Type> type_dir_t;
static type_dir_t types;
};
完整代码可用as gist on github .
在 C++ 中,对于逻辑上不相关的类通常不赞成使用公共(public)基类,尽管可以说这与鼓励使用公共(public)基类的 CRTP/mixins 类似。所以我想说,如果您不关心现有类型,这种方法不一定有什么问题。
关于c++ - 定义内省(introspection) C++ 类层次结构描述的有效方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10619164/