【发布时间】:2019-04-01 14:51:48
【问题描述】:
有时我会面临这样一种情况,即我获得了一个具有受保护静态成员的类(无法修改),例如
struct foo {
protected:
static const int x = 42;
static const int y = 101;
static const int z = 404;
// ... and more ...
};
不幸的是,我需要访问这些成员,而不是在派生类中,而是在其他代码中。我是这样写的:
struct bar : foo {
static const int x = foo::x;
static const int y = foo::y;
static const int z = foo::z;
};
但感觉相当笨拙。从长远来看,应该修改类foo 以提供对这些常量的访问,但只要不是这种情况,我希望有更好的东西。我可以沿着
int x = SOME_MACRO_VOODOO(foo,x);
不过,我想知道是否有办法避免使用宏。我尝试了很多方法,例如这个
struct f {
protected:
static const int x = 42;
};
template <typename T, int T::*P>
struct bar : f {
int get_value() { return this->*P;}
};
int main() {
bar<f,&f::x>().get_value();
}
失败是因为&f::x 不是指向成员的指针,而只是int *,当然f::x 是不可访问的:
prog.cc: In function 'int main()':
prog.cc:12:16: error: could not convert template argument '& f::x' from 'const int*' to 'int f::*'
bar<f,&f::x>().get_value();
^
prog.cc:12:5: error: 'const int f::x' is protected within this context
bar<f,&f::x>().get_value();
^~~~~~~~~~~~
prog.cc:3:22: note: declared protected here
static const int x = 42;
【问题讨论】:
-
这些数据受到保护而不是公开是有原因的。有一份由开发人员编写的合同,而您正试图破坏它。
-
@MatthieuBrucher 问题是合同已经“损坏”,修复它需要时间和漫长的过程,在此之前我需要一种解决方法来访问应该可以访问的东西,但它不是
-
看这两篇文章:gotw.ca/gotw/076.htm,bloglitb.blogspot.com/2010/07/…,了解如何颠覆访问控制。