2014-03-04 122 views
1

假设您需要通过类文字或通过该类的继承对象来访问结构/类的成员。它可能看起来是这样的:多态:通过类文字或对象访问静态成员

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; 
+2

'模板结构组件{长信息getKey(){返回键; }}; struct FooComponent:Component <0x1> {};' –

+0

@IgorTandetnik对不起,我写了我的答案,然后我看到了您的评论。 – iavr

回答

2

扩展@ 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 
+0

实施它,就像一个魅力。这是一个非常干净的方法!谢谢,很好的回答。 – Fault

2

静态多态性是你的朋友在这里:

template <long K = 0> 
struct Component { 
    static constexpr long key = K; 
    long getKey() {return key;}; 
}; 

struct FooComponent : Component <0x1> {}; 

struct BarComponent : Component <0x2> {}; 
+0

好吧,这不是一回事。原来有一个类层次结构。不确定这是否是一项要求,但值得一提。 –

+0

谢谢Karoly,这是我没有想到的要求。我编辑了这个问题。 – Fault