[英]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 由于类中的静态const数据实际上只是常量的命名空间糖,我认为
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++? 这样的事情在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: 您无法在C ++中重新打开结构/类定义,因此您可以做的最好的事情是创建第三方结构的派生版本并以这种方式添加常量:
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. 否则,您可以使用基于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;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.