gpt4 book ai didi

c++ - 模板参数中的访问控制

转载 作者:IT老高 更新时间:2023-10-28 22:14:41 28 4
gpt4 key购买 nike

灵感来自 this answer ,号称要颠覆门禁系统,我写了下面这个最小版的hack

template<typename T>
inline T memptr{};

template<auto Val>
struct setptr
{
struct setter { setter() { memptr<decltype(Val)> = Val; } };
static setter s;
};

template<auto Val>
typename setptr<Val>::setter setptr<Val>::s{};

然后是 used as

class S
{
int i;
};

template struct setptr<&S::i>;

auto no_privacy(S& s)
{
return s.*memptr<int S::*>;
}

为什么不 template struct setptr<&S::i>;违反访问控制?

是因为[class.access]

Access control is applied uniformly to all names, whether the names are referred to from declarations or expressions.

具体不包括实例化?在这种情况下,为什么不包括实例化?

勘误表:显式实例化也归类为声明。

最佳答案

来自 [temp.spec]/6 (强调我的):

The usual access checking rules do not apply to names in a declaration of an explicit instantiation or explicit specialization, with the exception of names appearing in a function body, default argument, base-clause, member-specification, enumerator-list, or static data member or variable template initializer. [ Note: In particular, the template arguments and names used in the function declarator (including parameter types, return types and exception specifications) may be private types or objects that would normally not be accessible. — end note  ]

所以你看到的这种技术滥用了这条规则,主要是为了允许类的实现者专门化具有私有(private)类型或其他私有(private)实体的模板(例如特征)

关于c++ - 模板参数中的访问控制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54909496/

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