Re: Local class problem
eric wrote:
The following code does compile with Visual C++ express 2008 but not
with g++ version 4.1.3:
#include <vector>
#include <algorithm>
void foo(std::vector<int>& values)
{
struct filler {
filler() : val_(0) {}
int operator()() { return ++val_; }
int val_;
};
std::generate(values.begin(), values.end(), filler());
}
g++ gives the following error:
local-class.cpp: In function 'void foo(std::vector<int,
std::allocator<int> >&)':
local-class.cpp:12: error: no matching function for call to
'generate(__gnu_cxx::__normal_iterator<int*, std::vector<int,
std::allocator<int> > >, __gnu_cxx::__normal_iterator<int*,
std::vector<int, std::allocator<int> > >, foo(std::vector<int,
std::allocator<int> >&)::filler)'
What's the problem? Visual C++ (and I as well) does certainly know
what function to call. Why doesn't g++? What can be done about it?
Note that struct filler is a throw-away class that I don't want to
have in the global namespace and that I don't even want to have as
a nested class in some other encompassing class of which foo()
might be a method.
You can't use local classes as template parameters, because the
current standard doesn't say what should happen. Formally, the
template parameter must have "external linkage", to guarantee that an
instantiation is unique.
The problem comes up with this code:
void foo(std::vector<int>& values)
{
struct filler {
// whatever
};
std::generate(values.begin(), values.end(), filler());
}
void bar(std::vector<int>& values)
{
struct filler {
// same or different?
};
std::generate(values.begin(), values.end(), filler());
}
Does this create one or two generate functions? We don't know.
For what it's worth, VC++ will also reject the code if you select
"Disable Language Extensions" (or use option /Za). For historical
reasons, VC++ allows lots of non-standard code just to be nice. But it
isn't very nice!
Also, I believe that the next revision of the C++ standard will define
the meaning of your code, making it allowed in the future.
Bo Persson
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]