[英]Add static const data to a struct already defined
由於類中的靜態const數據實際上只是常量的命名空間糖,我認為
struct A {
float a;
struct B {
static const int b = 2;
};
};
相當於
struct A {
float a;
};
struct A::B {
static const int b = 2;
};
或類似的東西。 這樣的事情在C ++中是可能的嗎? 能夠使用這樣的信息標記我從第三方庫中提取的類定義對我有用。
您無法在C ++中重新打開結構/類定義,因此您可以做的最好的事情是創建第三方結構的派生版本並以這種方式添加常量:
struct My_A : public A
{
static const int b = a;
};
否則,您可以使用基於struct typeid的鍵維護常量的映射。
我也喜歡喬治的想法。
不,你不能只是那樣重新定義類。
如果要標記已定義的類,可以使用例如模板特化來非侵入地執行:
template<class T> struct tagged;
template<> struct tagged<A> {
static const int b = 42;
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.