compilation error with function template


S

subramanian100in

I want to learn the use of value_type member of the standard library
container.
For this, I want to write a template to sum the elements in a
container, say for example vector<int>.( I do not want to use
accumulate algorithm in this example program just for learning
purpose).
I try to write 'function template' because I want this program to run
for any container of objects of user-defined class types also, with
appropriate operator+() defined.

#include <cstdlib>
#include <iostream>
#include <vector>

using namespace std;

template <typename Container>
Container::value_type add(const Container& c)
{
Container::value_type val = Container::value_type();

for (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;

return EXIT_SUCCESS;
}


Suppose this program is named x.cpp and I compile using g++ 3.4.3, as
g++ -std=c++98 -pedantic -Wall -Wextra x.cpp

Then I get the following compilation errors:
x.cpp:8: error: expected constructor, destructor, or type conversion
before "add"
x.cpp:8: error: expected `;' before "add"
x.cpp: In function `int main()':
x.cpp:28: error: `add' undeclared (first use this function)
x.cpp:28: error: (Each undeclared identifier is reported only once for
each function it appears in.)

Kindly help me in removing the compilation errors.

I have written
Container::value_type val = Container::value_type();
Here since I need to have the initial value of 'val' to be set for
subsequent use in 'val = val + *ci', I use the default ctor
Container::value_type(). Is this approach correct ?

Thanks
V.Subramanian
 
Ad

Advertisements


Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top