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!
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.
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.
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).
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'.
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
.
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