storing mem_fun in a standard container
Is there a way to create a vector< mem_f开发者_StackOverflow社区un_t< ReturnType, MyClass > >
?
The error i'm seeing is:
error C2512: 'std::mem_fun1_t<_Result,_Ty,_Arg>' : no appropriate default constructor available
I really can't see why it would not work, but it's actually a pretty ugly solution. Just take vector<function<ReturnType(MyClass*)>>
and be without those issues present in C++03 binders.
You certainly can create such a vector.
#include <vector>
#include <functional>
#include <iostream>
struct MyClass
{
int a() { return 1; }
int b() { return 2; }
};
int main()
{
std::vector<std::mem_fun_t<int, MyClass> > vec;
vec.push_back(std::mem_fun(&MyClass::a));
vec.push_back(std::mem_fun(&MyClass::b));
MyClass x;
for (size_t i = 0; i != vec.size(); ++i) {
std::cout << vec[i](&x) << '\n';
}
}
If you are having problems, read the error message carefully. For example, std::mem_fun
can return all sorts of wrappers, depending on what you pass to it.
Or indeed, switch to boost's or C++0x's function
.
Edit: With this particular error message, I assume that you are doing something that invokes the default constructor for contained type (e.g resize
or specifying the size with the vector's constructor). You can't use those functions.
mem_fun_t
meets the requirements to be stored in a container (it is copy-constructible and assignable), so the answer is yes.
However, it isn't default-constructible or comparable, so there are some things you can't do with a container of them, including:
- Resizing, unless you provide a value to fill with
- Constructing with a non-zero size, unless you provide a value to fill with
- Comparing containers
The error you are seeing comes from trying to either resize, or construct with a size.
精彩评论