简体   繁体   中英

Add static const data to a struct already defined

Since static const data inside a class is really just namespace sugar for constants I would think that

struct A {
    float a;

    struct B {
       static const int b = 2;
    };

 };

would be equivalent to

struct A {
    float a;
};

struct A::B {
    static const int b = 2;
};

or something similar. Is something like this possible in C++? It would be useful for me to be able to tag class definitions that I'm pulling in from third party libraries with information like this.

You can't reopen struct/class definitions in C++, so the best you can do is create derived versions of the third party structs and add your constants that way:

struct My_A : public A 
{
    static const int b = a;
};

Otherwise, you could maintain a map of your constants with keys based on struct typeid.

I do like Georg's idea as well.

No, you can't just redefine classes that way.

If you want to tag already defined classes, you could do that non-intrusively using eg template specializations:

template<class T> struct tagged;

template<> struct tagged<A> {
    static const int b = 42;
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM