compilation error with function template

Discussion in 'C++' started by subramanian100in@yahoo.com, India, Apr 13, 2009.

  1. , India

    , India Guest

    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
    , India, Apr 13, 2009
    #1
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Aman
    Replies:
    7
    Views:
    382
    Jonathan Mcdougall
    Oct 2, 2003
  2. , India
    Replies:
    2
    Views:
    315
  3. C__chp
    Replies:
    4
    Views:
    501
    Puppet_Sock
    Feb 15, 2008
  4. sunil
    Replies:
    1
    Views:
    369
    Ian Collins
    Aug 15, 2008
  5. , India
    Replies:
    2
    Views:
    287
    mingze zhang
    Aug 30, 2010
Loading...

Share This Page