zero value for all types?

Viewed 1630

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 ?
}
4 Answers

Your criterias are not possible in classical C++. None of the answers will totally work. Since TYPE t() and TYPE t {} both call the default constructor. Thus, if there is no default constructor, then there will be a compile failure.

You will have to do something like ZeroMemory.

But keep in mind that default constructors are run at run-time anyhow.

Related