好吧,也许不是最好的头衔,但这是交易:
我有一个模板界面:
template<typename T>
class MyInterface
{
public:
struct MyStruct
{
T value;
};
virtual void doThis(MyStruct* aPtr) = 0;
};
和实施:
template <typename T>
class MyImpl : public MyInterface<T>
{
public:
void doThis(MyStruct* aPtr)
{
} // doThis
};
然而,编译器抱怨:
In file included from MyTest.cpp:3:0:
MyImpl.h:7:17: error: ‘MyStruct’ has not been declared
void doThis(MyStruct* aPtr)
为什么?
答案 0 :(得分:3)
以下为我编译:
template<typename T>
class MyInterface
{
public:
struct MyStruct
{
T value;
};
virtual void doThis(MyStruct* aPtr) = 0;
};
template <typename T>
class MyImpl : public MyInterface<T>
{
public:
void doThis(typename MyInterface<T>::MyStruct* aPtr)
{
}
};
int main() {
MyImpl<int> t;
}
主要变化是,您需要确定MyStruct
中定义了MyInterface<T>
。
由于编译器无法确定模板化子类型的标识符类型,因此必须使用typename
关键字来帮助它。 (有关typename的更多详细信息,请参阅When is the "typename" keyword necessary?)