为什么GCC允许从全局模板功能中看到私有嵌套的模板类/结构? [英] Why does GCC allow private nested template classes/structs to be visible from global template functions?

查看:53
本文介绍了为什么GCC允许从全局模板功能中看到私有嵌套的模板类/结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白为什么在下面的代码中,我可以创建函数 print_private_template ,而编译器抱怨 print_private_class :

I don't understand why in the following code, I am allowed to create the function print_private_template while the compiler complains about print_private_class:

#include <cstdio>

class A
{
    private:
        template <unsigned T>
        struct B
        {

        };

        struct C
        {

        };

    public:
        template <unsigned T>
        B<T> getAb()
        { 
            return B<T>();
        }

        C getAc()
        { 
            return C();
        }
};

template<unsigned T>
void print_private_template(const A::B<T> &ab)
{
    printf("%d\n", T);
}

void print_private_class(const A::C &ac)
{
    printf("something\n");
}

int main(int, char**)
{
    A a;

    print_private_template(a.getAb<42>());

    print_private_class(a.getAc());

    return 0;
}

这是预期的行为吗?编译器错误/扩展名?

Is this an expected behaviour? a compiler bug/extension?

请明确一点,我的目标是使两者上的编译器错误都使用 print_private_template print_private_class .

Just to be clear, my goal is to make the compiler error on both the usage of print_private_template and print_private_class.

推荐答案

Comeau 确实给出了错误(当您注释掉 print_private_class 函数及其在严格的C ++ 03模式下的调用时.

Comeau does give an error (when you comment out the print_private_class function and its call in strict C++03 mode.

ComeauTest.c(31):错误:无法访问类模板"A :: B"(在第7行声明)无效print_private_template(const A :: B& ab)^根据以下示例在"print_private_template"的实例化期间检测到第45行的模板参数< 42U>

ComeauTest.c(31): error: class template "A::B" (declared at line 7) is inaccessible void print_private_template(const A::B &ab) ^ detected during instantiation of "print_private_template" based on template argument <42U> at line 45

Windows上的

G ++ 4.5不会使用 -std = c ++ -Wall -pedantic 报告任何错误.

G++ 4.5 on Windows does not report any error with -std=c++ -Wall -pedantic though.

您的类 A :: C 和类模板 A :: B< T> 都具有与其他任何普通成员相同的可见性.因此, print_private_class print_private_template 都需要诊断.

Your class A::C and class template A::B<T> both have the same visibility as any other normal members. Hence, both print_private_class and print_private_template require a diagnostic.

11.8嵌套类 [class.access.nest]

11.8 Nested classes [class.access.nest]

1 嵌套类是成员,因此具有与任何其他成员相同的访问权限.的成员封闭类对嵌套类的成员没有特殊访问权限;通常的访问规则(第11条)应该被遵守.

1 A nested class is a member and as such has the same access rights as any other member. The members of an enclosing class have no special access to members of a nested class; the usual access rules (Clause 11) shall be obeyed.

这篇关于为什么GCC允许从全局模板功能中看到私有嵌套的模板类/结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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