【发布时间】:2012-08-15 17:18:44
【问题描述】:
我最近遇到了一些 C++ 代码,在父类中 typedefed a struct。但是,它似乎在子类中不可用,即使它没有标记为private(它是protected)。我在下面创建了一个最小的工作示例(如下)来演示此失败。我已经公开了所有内容,但仍然失败。给出的错误是(使用g++):
B.h:8: error: expected ',' or '...' before '&' token
B.h.8: error: ISO C++ forbids declartion of 'Datum' with no type
A.h(编译)
template<typename S, typename T> class A {
public:
typedef struct {
S x;
T y;
} Datum;
};
B.h(不编译)
#include "A.h"
template<typename Q> class B : public A<Q, Q> {
public:
void output(const Datum& dat);
};
B.h(编译)
#include "A.h"
template<typename Q> class B : public A<Q, Q> {
public:
typedef struct {
Q x;
Q y;
} Datum;
void output(const Datum& dat);
};
为什么B.h 的第一个版本无法编译?第二个是安全的选择吗?有没有更好(更简洁或惯用)的方法来处理这个问题?
【问题讨论】:
-
我相信
A.h确实不按书面方式编译。 -
@KerrekSB 谢谢。我处于无法复制和粘贴的情况,所以我犯了一个错误。现已修复。
-
@BoPersson 答案是相关的,但我想说这个问题不是重复的,因为如果我知道这个问题有多密切相关,我可能已经知道我的解决方案了。 IE。我想说答案相似,但问题不同。
-
@Kazark - 这是一个见仁见智的问题。 :-) 关于为什么来自模板化基类的名称不可见有很多问题——都是出于同样的原因。链接到问题的
typedef与此相同,但问题很普遍。
标签: c++ templates inheritance name-lookup