2

I wrote two pieces of code as below, and the compiler output an error. But I don't know why.

The template function file:

#ifndef INCLUDE_XXXX
#define INCLUDE_XXXX
#include <vector>
using namespace std;

namespace testns {
    template< typename T > 
    inline T ssum(std::vector<T> v) 
    {
      T _sum;
      std::vector<T>::iterator iter;           // <-------------- **********
      for (iter=v.begin(); iter!=v.end(); ++iter) {
         _sum=_sum+(*iter);
      }
      return _sum;
    }; // ssum
}
#endif

The main code is below,

#include <vector>
#include <iostream>
#include "wyko.hpp"
using namespace std;

int main(){
   vector<double> v;
   v.push_back(3.0);
   v.push_back(2.0);
   v.push_back(1.0);
   cout<<testns::ssum<double>(v)<<endl;;
   return 0;
}

When I compile it, the following is output:

wyko.hpp:14: error: expected `;' before ‘iter’
wyko.hpp:15: error: ‘iter’ was not declared in this scope

I know the problem lies in the noted line and about the <T> but don't know how to fix it.

Thx

didierc
  • 14,572
  • 3
  • 32
  • 52
Yunzhi Ma
  • 662
  • 6
  • 9
  • That compiles ok for me in VS 2012, the only problem is that `_sum` is uninitialized. And you should be passing the vector by reference, not value. – Jonathan Potter Aug 05 '13 at 20:23
  • 2
    Requires type name., see http://stackoverflow.com/questions/11969421/template-error-nontype-with-t-t-is-not-a-type-name/11969456#11969456 – hmjd Aug 05 '13 at 20:27
  • 2
    @Jonathan VS is cheating. This isn’t valid C++. – Konrad Rudolph Aug 05 '13 at 20:28
  • You should remove the `using namespace std;` line in the header file, since you are using the qualifier anyway, and it's usually a bad idea to have that sort of thing in a header. – didierc Aug 05 '13 at 20:32
  • Also, you probably don't need to qualify your function when you use it: the compiler should be able to infer the type `T` from the argument type (ie. no need to write `ssum`, `ssum` should suffice). – didierc Aug 05 '13 at 20:35
  • 1
    Note there's [`std::accumulate`](http://en.cppreference.com/w/cpp/algorithm/accumulate) which does the same job. – dyp Aug 05 '13 at 20:42

1 Answers1

0

Fix:-

T _sum =0; //initialize it
typename std::vector<T>::iterator iter;  
// ^^^add typename
sehe
  • 374,641
  • 47
  • 450
  • 633
P0W
  • 46,614
  • 9
  • 72
  • 119