Add static const data to an already defined structure

Since static constant data inside a class is actually just a namespace sax for constants, I would think that

struct A {
    float a;

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

 };

will be equivalent

struct A {
    float a;
};

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

or something similar. Is this possible in C ++? It would be useful if I could mark the definitions of classes that I take out from third-party libraries with such information.

+3
source share
2 answers

You cannot reopen struct / class definitions in C ++, so it’s best to create derived versions of third-party structures and add your constants as follows:

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

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

I like the idea of ​​Georg.

+3

, .

, , , , :

template<class T> struct tagged;

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

Source: https://habr.com/ru/post/1745690/


All Articles