假设您需要通过类文字或通过该类的继承对象来访问结构/类的成员。它可能看起来是这样的:多态:通过类文字或对象访问静态成员
struct Component {
static const long key = 0;
virtual long getKey() {return key;};
};
struct FooComponent : Component {
static const long key = 0x1;
virtual long getKey() {return key;};
};
struct BarComponent : Component {
static const long key = 0x2;
virtual long getKey() {return key;};
};
通过上述,key
可以访问或者通过:
long key = FooComponent::key;
或
FooComponent foo;
long key = foo.getKey();
现在我的问题是:是否有一些清洁剂,减少多余的方式来达到上述目的?理想情况下,virtual long getKey() {return key;};
只需要指定一次,而不是每个继承类。
编辑:
类层次结构是重要。该组件存储在一个容器中,在我的情况下,unordered_map:
std::unordered_map<long, std::unique_ptr<Component>> components;
'模板结构组件{长信息getKey(){返回键; }}; struct FooComponent:Component <0x1> {};' –
@IgorTandetnik对不起,我写了我的答案,然后我看到了您的评论。 – iavr