1

when compiling with mingw32-g++, there is error: no matching function for call to 'for_each(int [9], int*, main()::Output)', but can do well in vs2005?

#include <iostream>
#include <algorithm>

int main() {

  struct Output {
      void  operator () (int v) {
           std::cout << v << std::endl; 
       }
  };

  int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
  std::for_each(a, a + sizeof(a)/sizeof(a[0]), Output());

  return 0;
}
hu wang
  • 411
  • 3
  • 12

2 Answers2

5

In pre-C++11 version of the language types used as template arguments were required to have linkage. Local class declarations in C++ have no linkage, which is why they can't be used as template arguments in C++98/C++03. In those versions of the language you have to declare your class in namespace scope.

The linkage requirement was removed in C++11. Your code is valid from C++11 point of view. Apparently, you are compiling in pre-C++11 mode.

AnT
  • 302,239
  • 39
  • 506
  • 752
  • Unless you happen to have a C++11 conformat compiler (or one that doesn't know the rules - VS2005). – Bo Persson Aug 13 '12 at 06:50
  • @Flexo: Why would it be a problem? Argument deduction mechanism will make `for_each` to receive its last argument *by value*. No problem whatsoever. – AnT Aug 13 '12 at 06:55
3

You have to declare the struct outside of main. See this question for an explanation.

Community
  • 1
  • 1
Björn Pollex
  • 72,744
  • 28
  • 189
  • 274