Storing mem_fun in a standard container

Is there any way to create vector< mem_fun_t< ReturnType, MyClass > > ?

The error I see is:

 error C2512: 'std::mem_fun1_t<_Result,_Ty,_Arg>' : no appropriate default constructor available 
+4
source share
3 answers

Of course, you 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 have any problems, read the error message carefully. For example, std::mem_fun can return all kinds of wrappers, depending on what you pass to it.

Or, really, switch to boost or C ++ 0x function .


Edit: with this specific error message, I assume that you are doing something that calls the default constructor for the contained type (e.g. resize or specifying a size using a vector constructor). You cannot use these features.

+3
source

I really don’t understand why this will not work, but this is actually a rather ugly solution. Just take vector<function<ReturnType(MyClass*)>> and be without these problems present in C ++ 03 binder files.

+4
source

mem_fun_t meets the requirements that must be stored in the container (it can be copied and assigned), so the answer is yes.

However, it is not constructive or comparable by default, so there are some things you cannot do with their container, including:

  • Resize if you do not provide a fill value with
  • Building with a non-zero size if you do not provide a value to fill with
  • Container comparison

The error you see is due to an attempt to resize or create a size.

+2
source

All Articles