如何正确初始化模板类型的变量? [英] How to correctly initialize variable of template type?

查看:377
本文介绍了如何正确初始化模板类型的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

建议我有一个如下的模板函数:

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 == class,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屋!

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