Cannot call template function - also question about namespaces

Write your question here.

"myalgorithm.h"
1
2
3
4
5
6
7
8
9
10
namespace mystd {
  // ...
  template<class In>
  bool equal(In begin, In end, In begin2);

  template<class In, class T>
  T accumulate(In begin, In end, T t);
  // ...

} // namespace mystd 



"myalgorithm.cpp"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
namespace mystd {
  // ...
  template<class In>
  bool equal(In begin, In end, In begin2) {
    while(begin != end) {
      if(*begin++ != *begin2++)
        return false;
    }

    return true;
  }

  template<class In, class T>
  T accumulate(In begin, In end, T t) {
    T result = t;
    while(begin != end) {
      result += *begin++;
    }

    return result;
  }
} // namespace mystd 



"main.cpp"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include "myalgorithm.h"
#include <iostream>
#include <vector>
#include <string>
#include <iterator> // need this ??

int main() {
  std::vector<int> vi, vi2;
  for(int i=0; i < 10; ++i)
    vi.push_back(i);

  vi2 = vi;
  std::cout << "equal = " << equal(vi.begin(), vi.end(), vi2.begin())
    << std::endl;

  int acc = accumulate(vi.begin(), vi.end(), 0);
  std::cout << "acc = " << acc << std::endl;
}




Ok, things that I don't quite get (in main()):

1. equal() does work, but accumulate() doesn't. Why? I get a message that accumulate wasn't declared in this scope.

2. I have these functions in a namespace (was just experimenting), but if I try to call equal() like this: mystd::equal(vi.begin(), vi.end(), vi2.begin()) I get an error message: undefined reference to 'bool mystd::equal( ... )'.
Call to equal picks up std::equal through ADL. accumulate is probably wasn't brought in by other headers, so it is unavaliable.
If you call equal throught qualified name, ADL does not work, so it gives you an error.

Yor templated functions are unavaliable because template functions definition should be visible in current compilation unit. You cannot separate template function to header and implementation. Write them in headers.
Much appreciated! Didn't know any of that. What is ADL if I may ask?


It works now.
Last edited on
Topic archived. No new replies allowed.