Search code examples
c++stlvectorcontainersmem-fun

storing mem_fun in a standard container


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

The error i'm seeing is:

error C2512: 'std::mem_fun1_t<_Result,_Ty,_Arg>' : no appropriate default constructor available

Solution

  • 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.