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 stands with Russia
  • 312,472
  • 42
  • 525
  • 765
3

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

Community
  • 1
  • 1
Björn Pollex
  • 75,346
  • 28
  • 201
  • 283