gpt4 book ai didi

c++ - 为什么我不能将 protected 嵌套类用作另一个 protected 嵌套类的模板参数?

转载 作者:搜寻专家 更新时间:2023-10-31 00:40:25 28 4
gpt4 key购买 nike

在了解到嵌套类是嵌套类的成员并因此可以完全访问嵌套类的成员这一事实后(至少对于 C++11,请参见 here),我在尝试创建嵌套类模板:

#include <iostream>

using namespace std;

// #define FORWARD

class A {

// public: // if FooBar is public, the forward declared version works
protected:
enum class FooBar { // line 11, mentioned in the error message
foo,
bar
};

protected:
#ifdef FORWARD
// forward declaration only
template< FooBar fb = FooBar::foo >
struct B;
#else
// declaration and definition inline
template< FooBar fb = FooBar::foo >
struct B{
void print(){ cout << A::i << (fb==FooBar::foo ? " foo" : " not foo") << endl;};
};
#endif

public:
B<>* f;
B<FooBar::bar>* b;
private:
static const int i = 42;
};

#ifdef FORWARD
// definition of forward declared struct
template< A::FooBar fb>
struct A::B{
void print(){ cout << A::i << (fb==FooBar::foo ? " foo" : " not foo") << endl; };
}; // line 41, mentioned in the error message
#endif


int main(int argc, char **argv)
{
A a;
a.f->print();
a.b->print();
return 0;
}

这应该(并且确实)输出:

42 foo
42 not foo

问题

如果 #define FORWARD 未注释,即 FORWARD 已定义,为什么此代码无法编译?

我得到的错误(来自 gcc 4.7.2)是

main.cpp:11:14: error: ‘enum A::FooBar’ is protected
main.cpp:41:2: error: within this context

来自answer到更早的question我了解到 BA 的成员,应该可以访问它的(私有(private))成员(它确实打印了 A::i)。那么为什么不能在类外声明中访问 A::FooBar 呢?

背景

这显然是一些其他代码的最小示例,其中 header 和实现是分开的。我只想转发声明嵌套类模板 B 以使类 A 的接口(interface)更具可读性,因为那时我可以将模板类的实现推到头文件的末尾(即通过取消注释 #define FORWARD 获得的行为/设置)。所以,是的,这是一个相当表面上的问题——但我相信这表明我不明白发生了什么,因此我很想了解这个,但为什么呢? .

最佳答案

您可以将示例简化为:

class A
{
private:
enum FooBar { foo };

public:
template< FooBar fb = foo >
struct B;
};

template< A::FooBar >
struct A::B
{
};

A::B<> a;

这是合法的,正如 DR 580 所阐明的那样, 并被 Clang++ 接受,因此看起来 G++ 尚未实现该解决方案。

我已将其报告为 GCC PR 56248还报告了Clang PR 15209因为 Clang 也没有完全实现 DR 580。

关于c++ - 为什么我不能将 protected 嵌套类用作另一个 protected 嵌套类的模板参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14761672/

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