带有默认值的模板返回类型 [英] Template Return Type with Default Value
问题描述
所以在编写一个C ++模板类时,我定义了一个返回模板类型对象的方法,如下所示:
So in writing a C++ template class, I have defined a method that returns an object of the templated type, as such:
template <typename T>
class Foo
{
public:
T GetFoo()
{
T value;
//Do some stuff that might or might not set the value of 'value'
return value;
}
};
int main() {
Foo<int> foo;
foo.GetFoo();
return 0;
}
这会产生以下警告:
prog.cpp: In member function ‘T Foo<T>::GetFoo() [with T = int]’:
prog.cpp:15: warning: ‘value’ is used uninitialized in this function
我理解为什么会发生这种情况 - 作为 GetFoo
一部分的未初始化 int
。事情是,如果我使用 Foo< SomeClass>
,行 T值;
将初始化 value
使用 SomeClass
的默认构造函数。
I understand why this is happening - I am returning an uninitialized int
as part of GetFoo
. The thing is, if I were to use Foo<SomeClass>
, the line T value;
would initialize value
using the default constructor of SomeClass
.
通过执行以下操作抑制此警告:
I have managed to suppress this warning by doing the following:
T GetFoo()
{
T value = T();
//Do some stuff that might or might not set the value of 'value'
return value;
}
这似乎适用于原始类型(例如 int
和 float
)和类,至少只要该类有一个默认的构造函数和拷贝构造函数。我的问题是 - 这是接受的解决这个问题的方法吗?是否有任何副作用我应该知道吗?
This seems to work for primitive types (such as int
and float
) and classes, at least so long as that class has a default constructor and copy constructor. My question is - is this the accepted way of solving this problem? Are there any side effects of this I should know about?
推荐答案
听起来OK,如果类没有复制构造函数,无法返回。
Sounds OK, if the class has no copy constructor, you will not be able to return it anyway.
这篇关于带有默认值的模板返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!