Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Default initialize an integral type in a template function

Tags:

c++

templates

For educational purposes I am wrting my own C++ numerical vector template class. I want to be able to write (v, w) for the dot product of two vectors and consequently overload operator,() as follows:

template<class T>
const T Vector<T>::operator,(const Vector<T>& v) const
{
    assertEqualSize(v);

    T t;
    for(size_t i=0; i<numElements; i++) {
        t += elements[i] * v[i];
    }
    return t;
}

My question now is: how do I properly initialize t with a sensible value (e.g. 0.0 for Vector<double>)? I tried T t(); but then g++ tells me, e.g., that "double(*)()" cannot be converted to "const double" at the return statement and that operator+=() would not be defined for "(double(), double)".

Thank you very much!

like image 693
o.svensson Avatar asked Aug 08 '13 07:08

o.svensson


People also ask

Are structs default initialized?

Constructors are defined with a function name of this and have no return value. The grammar is the same as for the class Constructor. A struct constructor is called by the name of the struct followed by Parameters. If the ParameterList is empty, the struct instance is default initialized.

How do you declare a template function?

To instantiate a template function explicitly, follow the template keyword by a declaration (not definition) for the function, with the function identifier followed by the template arguments. template float twice<float>( float original ); Template arguments may be omitted when the compiler can infer them.

What does it mean to initialise a field to a default value in a class declaration?

In Java, an initializer with the declaration means the field is always initialized the same way, regardless of which constructor is used (if you have more than one) or the parameters of your constructors (if they have arguments), although a constructor might subsequently change the value (if it is not final).

When the actual code for a template function is generated?

A code for template function is generated when the function is instantiated. The functions are often instantiated when they are first time called (in the code), but there are other ways to instantiate a function - do a so-called 'explicit instantiation'.


1 Answers

What you need is termed value initialization, which has the effect of zero-initializing built-in types:

T t{};     // C++11
T t = T(); // C++03 and C++11

The reason this doesn't work

T t();

is that it is a declaration of a parameterless function called t, returning a T.

like image 90
juanchopanza Avatar answered Sep 21 '22 17:09

juanchopanza