如何正确初始化模板类型的成员变量? [英] How to correctly initialize member variable of template type?
本文介绍了如何正确初始化模板类型的成员变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
建议我具有如下模板功能:
suggest i have a template function like following:
template<class T>
void doSomething()
{
T a; // a is correctly initialized if T is a class with a default constructor
...
};
但是,如果T是原始类型,则变量a不会被初始化。我可以写T a(0),但是如果T是一个类,则无法使用。在两种情况下(T ==类,T == int,char,bool等)都可以初始化变量吗?
But variable a leaves uninitialized, if T is a primitive type. I can write T a(0), but this doesn't work if T is a class. Is there a way to initialize the variable in both cases (T == class, T == int, char, bool, ...)?
推荐答案
像这样:
T a{};
Pre-C ++ 11,这是最简单的近似值:
Pre-C++11, this was the simplest approximation:
T a = T();
但是它要求 T
是可复制的(尽管该副本肯定会被删除)。
But it requires T
be copyable (though the copy is certainly going to be elided).
这篇关于如何正确初始化模板类型的成员变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文