Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

zero value for all types?

In C++11, is there a way to initialize a value to zero for arithmetic and class types (with absolutely no overhead at running time for the arithmetic types) ?

template<typename T> void myFunction(T& x)
{
    x = 0; // How to make this works for T = double but also for T = std::string ?
}
like image 968
Vincent Avatar asked Aug 10 '12 12:08

Vincent


1 Answers

You could use the default constructor to "clear" a variable:

template<class T>
void clear(T &v)
{
    v = T();
}

This will work for all primitive types, pointers and types that has a default constructor and an assignment operator (which all classes will have by default, unless told not to, or they are made protected/private).

like image 181
Some programmer dude Avatar answered Oct 03 '22 05:10

Some programmer dude