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 ?
}
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With