문제

I am starting to use templates and I have what I imagine is a simple question but I was not able to solve it nor I was able to find a solution I can understand on the web.

I want a template which initializes a variable to some standard value, let say 0, (but It can be something different if needed). Up to now I wrote this simple code:

template <typename T> 
void InitVar( T& Var){

    Var = T(0);

};

This code works for simple numberic types of variable, int, double, etc... But it is not working for different kind of variables such as strings. I know that the problem is the T(0) command but I do not know how to substitute this with something more general.

In particular what I am interested in is a code which works on standard numeric variables and strings. Can someone help me?

도움이 되었습니까?

해결책

First off, that's assignment, not initialization.

Anyway, you can use value initialization: T()
This will zero initialize arithmetic types or call default constructor of class types.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top