使用返回不完整类型的函数作为默认参数 [英] Use function returning incomplete type as default argument
问题描述
当我尝试编译并运行此代码时(只有前三行才很重要):
When I try to compile and run this code (only the first three lines really matter):
class object;
object getObject();
void doSomething(object o = getObject());
class object{
public:
int num = 0;
};
object getObject(){
return {};
}
void doSomething(object o){
o.num = 5;
}
int main(){}
我明白了此错误:
main.cpp:3:39: error: invalid use of incomplete type 'class object'
void doSomething(object o = getObject());
^
main.cpp:1:7: note: forward declaration of 'class object'
class object;
^
如何在不更改所有顺序的情况下进行编译?在我的实际代码中,声明是在一起的,而定义则分布在多个文件中。
How would I get it to compile without changing the order of everything? In my actual code, the declarations are together while the definitions are spread out across several files. Is it possible to do solve without separating the declarations?
为什么在此阶段类型不完整怎么办?
Why does it matter if the type is incomplete at this stage?
推荐答案
如何在不更改所有顺序的情况下进行编译?
How would I get it to compile without changing the order of everything?
您不必更改一切的顺序,但是您确实需要更改事物的顺序。特别是,必须在调用 getObject
(在默认参数表达式中)之前定义 object
。
You don't have to change the order of everything, but you do need to change the order of something. In particular, object
must be defined before getObject
is called (in the default argument expression).
是否可以在不分隔声明的情况下进行求解?
Is it possible to do solve without separating the declarations?
object ,则声明可以与示例中的一样。
It's a bit unclear what this means, but if you define object
at the top, then the declarations can remain exactly as they are in your example.
另一种选择是在 object
定义之后使用默认参数重新声明该函数:
Another option is to re-declare the function with the default argument after object
definition:
class object;
object getObject();
void doSomething(object o);
class object{
public:
int num = 0;
};
void doSomething(object o = getObject());
这当然意味着在第一个声明之后但在重新声明之前的代码受益于默认参数。
This of course would mean that the code after the first declaration, but before re-declaration won't benefit from the default argument.
最后,有些技巧。模板实例化之前,模板中的表达式不需要完整,因此如果 doSomething
是函数模板,则您的示例可以正常工作:
Lastly, a bit of a trick. Expressions within templates don't need to be complete until the template is instantiated, so your example would work fine if doSomething
was a function template:
template<class T=void>
void doSomething(object o = getObject());
class object{};
object getObject(){
return {};
}
template<class T>
void doSomething(object o){}
当然,您不应模板只是为了解决这个问题,但这是在编写模板时要注意的一个方便细节。
Of course, you shouldn't make a template just to get around this issue, but this is a handy detail to be aware of when you do write templates.
这篇关于使用返回不完整类型的函数作为默认参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!