我正在做一个练习来理解C++的可访问性与可见性。
下面的代码显然不能编译,但理想情况下必须是这样。
B继承自A,模板参数为Node,Node为B私有。
template<typename T>
class A {...};
template<typename T>
class B: public A<B<T>::Node> {
private:
struct Node{ int x=42;};
};我的试探性是:
template<typename T>
class A {...};
template<typename T>
class B: public A<B<T>::N> {
private:
struct Node{ int x=42;};
public:
typedef Node N;
};我为这两个都获取了Error: type/value mismatch at argument 1 in template parameter list for ‘template class A’。
我真的对此感到困惑,非常感谢您的帮助。
发布于 2018-11-29 06:18:27
问题是,由于B<T>还没有完成,所以不能在该行中使用B<T>::Node。如果没有B的完整定义,编译器将无法使用嵌套类型。
如果您使用以下命令,错误会更清楚:
template<typename T>
class B: public A<typename B<T>::Node> {
private:
struct Node{ int x=42;};
};这样,g++就会用以下代码生成一个更容易理解的错误。
template<typename T>
class A {};
template<typename T>
class B: public A<typename B<T>::Node> {
private:
struct Node{ int x=42;};
};
int main()
{
B<int> b;
}编译器错误:
socc.cc: In instantiation of ‘class B<int>’:
socc.cc:13:11: required from here
socc.cc:6:7: error: invalid use of incomplete type ‘class B<int>’
class B: public A<typename B<T>::Node> {
^
socc.cc:6:7: note: declaration of ‘class B<int>’
socc.cc: In function ‘int main()’:
socc.cc:13:11: warning: unused variable ‘b’ [-Wunused-variable]
B<int> b;
^你评论说
更具体地说,问题是A是一个树,而B是一个类似数组的容器,它使用树结构将我定义的Node保存在内存中。因此容器需要在内部使用节点树。我想这或多或少是一种常见的数据结构设计,那么通常如何解决这个问题呢?
这需要聚合,而不是继承。
template<typename T>
class A { ... };
template <typename T>
class B {
private:
struct Node{ int x=42;};
A<Node> data;
};https://stackoverflow.com/questions/53528815
复制相似问题