Re: compilation error with direct-initialization
I have a doubt in the same program I posted originally in the
beginning of this thread.
Kindly bear with me.
To avoid declaring 'val' inside the function add(), I could have
written,
template <typename Container>
typename Container::value_type add(const Container& c,
typename Container::value_type val)
But for the sake of learning purpose only, suppose I do not use this
prototype.
Consider the following program x.cpp:
#include <cstdlib>
#include <iostream>
#include <vector>
#include <deque>
#include <string>
using namespace std;
template <typename Container>
typename Container::value_type add(const Container& c)
{
typename Container::value_type val =
typename Container::value_type();
/* typename Container::value_type val(
typename Container::value_type());
*/
for (typename Container::const_iterator ci = c.begin();
ci != c.end();
++ci)
val = val + *ci;
return val;
}
int main()
{
vector<int> c;
int i;
while (cin >> i)
c.push_back(i);
cout << "sum = " << add(c) << endl;
deque<string> d;
string str;
cin.clear();
while (cin >> str)
d.push_back(str + " ");
cout << "sum = " << add(d) << endl;
return EXIT_SUCCESS;
}
I compiled this program with g++3.4.3 as
g++ -std=c++98 -pedantic -Wall -Wextra x.cpp
There is no compilation error.
Suppose I want to call the function add() on a container with value-
type being a built-in type(as with the case vector<int> c;) as well a
class type (as with the case deque<string> d;).
Then I need to initialize the 'val' variable with an appropriate
default value because I am calculating
val = val + *ci;
I want to initialize 'val' with zero for built-in type argument to the
container and I want to call the default ctor for class type argument
to the container.
I cannot just write
typename Container::value_type val;
because, for built-in type for Container::value_type, this statement
will initialize 'val' with some garbage value.
So, I have to write
typename Container::value_type val = typename Container::value_type();
But for Container::value_type being class type, the above statement
performs copy-initialization. Copy-initialization MAY involve one copy
ctor. Is it possible to avoid this copy-initialization but at the same
time initialize 'val' to a default value of appropriate type - that
is, is there a syntax by which I can initialize 'val' directly for
Container::value_type being built-in type as well as class-type ? Or,
is the above original statement the only way(which means that copy-
initialization cannot be avoided at all times)?
Kindly explain.
Thanks
V.Subramanian