为什么在显式实例化中不适当地访问私有是合法的? [英] Why is it legal to inappropriately access privates in an explicit instantiation?

查看:185
本文介绍了为什么在显式实例化中不适当地访问私有是合法的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么会允许这样做:

//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
template<typename T>
struct invisible
{
    static typename T::type value;
};

template<typename T>
typename T::type invisible<T>::value;

//////////////////////////////////////////////////////////////////////////
template<typename T, typename T::type P>
class construct_invisible
{
    construct_invisible(){ invisible<T>::value = P; }
    static const construct_invisible instance;
};

template<typename T, typename T::type P>
const construct_invisible<T, P> construct_invisible<T, P>::instance;

//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
class A
{
public:
    A(int x) : m_X(x){}
private:
    int m_X;
};

//////////////////////////////////////////////////////////////////////////
struct A_x{ typedef int A::*type; };
template class construct_invisible<A_x, &A::m_X>;// <---- WHY DOES `&A::m_X` WORK HERE?

//////////////////////////////////////////////////////////////////////////
int main()
{
    A a(17);
    std::cout << a.*invisible<A_x>::value << '\n';
}

Credit转到 Johannes Schaub 。 (演示

Credit goes to Johannes Schaub for the above C++ abuse. (Demo)

是否有其他情况下您可以访问应该是你看不见的?这是标准中的一个bug吗?

Are there other cases you can access what should be invisible to you? Is this just a 'bug' in the standard?

推荐答案

这是让类的作者有私有成员可以显式实例化该成员或将其作为参数传递给你。

It is so that the author of the class that has the private member can explicitly instantiate that member or pass it as an argument as you just did.

编译器不知道谁在键盘前面,所以这里的访问检查非常保守。

The compiler has no idea who is in front of the keyboard, so the access checking here is rather conservative.

显式实例化中使用的参数得到特殊处理,因为没有机制让类作者在允许的上下文中显式实例化模板,或者以某种方式允许这样做与朋友声明。

Parameters used in explicit instantiation get special treatment because there is no mechanism for a class author to explicitly instantiate a template in an allowed context or to somehow permit doing so with a friend declaration.

这篇关于为什么在显式实例化中不适当地访问私有是合法的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆