Search code examples
c++c++11initializationzero

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

Solution

  • 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).