gpt4 book ai didi

c++ - 为什么 GCC 允许私有(private)嵌套模板类/结构从全局模板函数中可见?

转载 作者:太空狗 更新时间:2023-10-29 22:52:44 30 4
gpt4 key购买 nike

我不明白为什么在下面的代码中,允许我创建函数 print_private_template 而编译器却提示 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;
}

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

明确一点,我的目标是在 两个 上使用 print_private_templateprint_private_class 时使编译器出错。

最佳答案

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

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 的错误虽然。

你的类(class) A::C和类模板 A::B<T>两者都具有与任何其他普通成员相同的可见性。因此,print_private_classprint_private_template需要诊断。

11.8 Nested classes [class.access.nest]

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.

关于c++ - 为什么 GCC 允许私有(private)嵌套模板类/结构从全局模板函数中可见?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3784652/

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