2014-03-04 118 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