compilation error with direct-initialization
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.
The line
typename Container::value_type val = typename Container::value_type();
is copy-initialization. Am I correct ?
Instead of the above line, if I have the following line
typename Container::value_type val(typename Container::value_type());
I get compilation error. I tried this form to behave as direct-
initialization. Isn't this direct-initialization ?
Kindly explain what is wrong with direct-initialization syntax?
Alternatively I could have used the prototype,
template <typename Container>
typename Container::value_type add(const Container& c,
typename
Container::value_type val)
to avoid declaring 'val' inside the function. But I didn't do it for
learning purpose only.
Thanks
V.Subramanian