此代码无法编译:
struct s_t {
int a;
};
struct c_s_t {
const int a;
};
s_t s;
c_s_t *c_s = &s;
ibug@ubuntu:~ $ g++ -fsyntax-only t.cpp
t.cpp:10:15: error: cannot convert ‘s_t*’ to ‘c_s_t*’ in initialization
c_s_t *c_s = &s;
^
然而,这个编译完美:
int a, *pa = &a, **ppa = &pa, ***pppa = &ppa;
const int * const * const * const cpcpcpa = pppa;
我知道在任何级别上更具 CV 限定的指针可以在任何级别指向更少 CV 限定的对象,但是为什么结构不一样呢?
上面的问题陈述是一个更复杂问题的 MCVE,我的朋友试图在t_s_t<T>
和之间转换指针t_s_t<const T>
,其中t_s_t
是带有一个模板参数的模板结构类型typename
,并且T
是任意类型。