无效使用不完全型 [英] invalid use of incomplete type

查看:151
本文介绍了无效使用不完全型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在我的项目中使用一个子类的typedef,我在下面的例子中已经隔离了我的问题。

I'm trying to use a typedef from a subclass in my project, I've isolated my problem in the example below.

m错误?

template<typename Subclass>
class A {
    public:
    	//Why doesn't it like this?
    	void action(typename Subclass::mytype var) {
    		(static_cast<Subclass*>(this))->do_action(var);
    	}
};

class B : public A<B> {
    public:
    	typedef int mytype;

    	B() {}

    	void do_action(mytype var) {
    		// Do stuff
    	}
};

int main(int argc, char** argv) {
    B myInstance;
    return 0;
}

这是我得到的输出:

sean@SEAN-PC:~/Documents/LucadeStudios/experiments$ g++ -o test test.cpp
test.cpp: In instantiation of ‘A<B>’:
test.cpp:10:   instantiated from here
test.cpp:5: error: invalid use of incomplete type ‘class B’
test.cpp:10: error: forward declaration of ‘class B’


推荐答案

当实例化类模板时,它的成员函数的所有声明(而不是定义)也被实例化。当需要专门化的完整定义时,类模板将精确实例化。这是例子,当它被用作基类的情况下,例如,在你的情况。

The reason is that when instantiating a class template, all its declarations (not the definitions) of its member functions are instantiated too. The class template is instantiated precisely when the full definition of a specialization is required. That is the case when it is used as a base class for example, as in your case.

那么会发生什么, A< B> 实例化在

So what happens is that A<B> is instantiated at

class B : public A<B>

此时 B 类型(它是类定义的结束大括号之后)。但是, A< B> :: action 的声明要求 B 完成,因为它正在抓取范围:

at which point B is not a complete type yet (it is after the closing brace of the class definition). However, A<B>::action's declaration requires B to be complete, because it is crawling in the scope of it:

Subclass::mytype

你需要做的是将实例化延迟到 B 完成的某个点。这样做的一种方法是修改 action 的声明,使其成为成员模板。

What you need to do is delaying the instantiation to some point at which B is complete. One way of doing this is to modify the declaration of action to make it a member template.

template<typename T>
void action(T var) {
    (static_cast<Subclass*>(this))->do_action(var);
}

它仍然是类型安全的,因为如果 var 不是正确的类型,将 var 传递给 do_action 将失败。

It is still type-safe because if var is not of the right type, passing var to do_action will fail.

这篇关于无效使用不完全型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆