多态性:通过类文本或对象访问静态成员
Polymorphism: accessing static members via class literal or object
>假设您需要通过类文本或通过该类的继承对象访问结构/类的成员。它可能看起来像这样:
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;
扩展@iavr对新要求的回答:
struct Component {
virtual ~Component() {}
virtual long getKey() { return 0; }
};
template <int Key>
struct KeyedComponent : Component {
long getKey() { return Key; };
};
struct FooComponent : KeyedComponent<1> { };
struct BarComponent : KeyedComponent<2> { };
测试:
std::vector<std::unique_ptr<Component>> components;
components.emplace_back(new FooComponent());
components.emplace_back(new BarComponent());
for (auto& component : components) {
std::cout << component->getKey() << std::endl;
}
指纹:
1
2
静态多态性是你的朋友:
template <long K = 0>
struct Component {
static constexpr long key = K;
long getKey() {return key;};
};
struct FooComponent : Component <0x1> {};
struct BarComponent : Component <0x2> {};
相关文章:
- 按基类对象访问派生类资源时出错
- 使用基类对象访问派生的仅类方法
- 从 const 对象访问非 const 方法
- 如何在C++中使用类对象访问指针数据成员
- 如何通过不同的指针使用类的对象访问结构?(链表)(C++)
- 使用二进制搜索树中的迭代器对象访问左侧节点
- 为什么引用类型在使用临时对象访问时是左值
- 从父对象 c++ 访问子方法
- 无法通过指针或对象 c++ 访问受保护的成员
- 为什么可以从类中的对象访问类的私有变量
- 对类似"struct {double, int}"对象使用reinterpret_cast进行对象访问
- 通过无符号 char 别名进行对象访问,加载和存储时会发生什么?
- 从对象访问结构枚举
- 如何全局创建对象并使用该对象访问全局范围内的公共成员函数
- 在C 中,可以从第三个共享对象访问其他两个不同共享对象
- 如何在C 中提供一个可呼叫的对象访问,例如lambda
- C 向量对象访问
- C++是否可以从同级第二个派生对象访问第一个派生对象的受保护基础数据成员?
- 如何从类内实例化的对象访问私有变量
- 多态性:通过类文本或对象访问静态成员