gpt4 book ai didi

c++ - 为什么不允许非静态成员的地址作为模板非类型参数?

转载 作者:IT老高 更新时间:2023-10-28 12:54:35 25 4
gpt4 key购买 nike

template <int* ip> struct test {};

struct q {
static int a;
int b;

constexpr q(int b_) : b(b_) {}
};

int i;
constexpr q q0(2);

int main()
{
constexpr test<&i> t1; // Works fine
constexpr test<&q::a> t2; // Works
constexpr test<&q0.b> t3; // Does not work; address of non-static member?

return 0;
}

尽管模板参数 &q0.b 在编译时已知,但上述代码中 t3 的声明失败。一些谷歌搜索显示标准不允许这样做(第 14.3.2 节):

[Note: Addresses of array elements and names or addresses of non-static class members are not acceptable template-arguments.

X<&s.m> x4; // error: address of non-static membe

那么,尽管全局变量的非静态成员的地址是唯一的并且在编译时是已知的,但为什么标准明确不允许这样做呢?

最佳答案

首先,要使用指向子对象的指针/引用,您需要能够破坏它们。这是一项艰巨的任务。

第二个,也许更重要的是,来自 N4198 :

The restriction that the constant expression must name a complete object is retained to avoid aliasing problems with pointers to subobjects:

struct A { int x, y; } a;
template<int*> struct Z;
using B = Z<&a.x + 1>;
using C = Z<&a.y>;
// Are B and C the same type?

引用 Richard Smith ,

The answer "yes" is problematic because there are things you can do with a pointer to [a.y] that would have undefined behavior if performed on a pointer past the end of [a.x] The answer "no" is problematic because they (in typical implementations) represent the same address.

关于c++ - 为什么不允许非静态成员的地址作为模板非类型参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33443130/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com