如何正确使用for_each?

时间:2010-10-13 04:55:28

标签: c++ g++ metaprogramming functional-programming

我是STL中所有功能的新手。我试着做一些东西,但无论我如何尝试它都会失败。请评论:

#include <iostream>
#include <algorithm>

using namespace std;

class X
{
    public:
        void Print(int x)
        {
            cout << x << endl;
        }

        void Do()
        {
            int arr[] = {1, 2, 3, 4, 5};
            mem_fun1_ref_t<void, X, int> oF = mem_fun_ref<void, X, int>(&X::Print);
            binder1st<mem_fun1_ref_t<void, X, int> > oU = bind1st(oF, *this);
            for_each(arr, arr+5, oU);
        }
};

int main()
{
    X x;
    x.Do();
}

我收到此错误:

/usr/include/c++/4.3/backward/binders.h: In member function ‘typename _Operation::result_type std::binder1st<_Operation>::operator()(typename _Operation::second_argument_type&) const [with _Operation = std::mem_fun1_ref_t<void, X, int>]’:
/usr/include/c++/4.3/bits/stl_algo.h:3791:   instantiated from ‘_Funct std::for_each(_IIter, _IIter, _Funct) [with _IIter = int*, _Funct = std::binder1st<std::mem_fun1_ref_t<void, X, int> >]’
main.cpp:19:   instantiated from here
/usr/include/c++/4.3/backward/binders.h:121: error: no match for call to ‘(const std::mem_fun1_ref_t<void, X, int>) (const X&, int&)’
/usr/include/c++/4.3/bits/stl_function.h:632: note: candidates are: _Ret std::mem_fun1_ref_t<_Ret, _Tp, _Arg>::operator()(_Tp&, _Arg) const [with _Ret = void, _Tp = X, _Arg = int]
/usr/include/c++/4.3/backward/binders.h:121: error: return-statement with a value, in function returning 'void'

编辑:

PluginLoader.h

#include <string>                                           
#include <list>
#include <functional>

class Plugin;
//This class is an interface for loading the list of file names of shared objects.                                                                                                 
//Could be by loading all file names in a dir, or by loading filenames specified in a file.
class FileNameLoader                                        
{       
    public:                                                 
        virtual std::list<std::string>& LoadFileNames() = 0;
};

class PluginLoader                                          
{   
public:
    explicit PluginLoader();                                
    virtual ~PluginLoader();                                

    virtual bool Load();

    virtual bool LoadPlugins(FileNameLoader&);              
    virtual bool LoadFunctions();

    void SetLoadingPolicy(std::unary_function<std::string, void>*);

protected:
    list<std::string> l_FileNames;                          

private:
    explicit PluginLoader(const PluginLoader&);
    PluginLoader& operator=(const PluginLoader&);           

    bool LoadSharedObjects();
    void* LoadSharedObject(const std::string);              

    list<PluginFunction*> l_Functions;                      
    list<Plugin*> l_Plugins;                                

    std::unary_function<const std::string, void>*& p_LibLoader;                                                                                                                    
};                                                          

#endif // _PLUGIN_LOADER_HEADER_ 

PluginLoader.cpp

#include <PluginLoader.h>
#include <algorithm>
#include <dlfcn.h>

using namespace std;                                        

//**************************************************************************************************
PluginLoader::PluginLoader():
{
    mem_fun1_t<void, PluginFunction, int> oL(&PluginLoader::LoadSharedObject);
    p_LibLoader = new binder1st<mem_fun1_t<void, PluginFunction, int> > oFunctor(oL, this);
}   

//**************************************************************************************************
PluginLoader::~PluginLoader()
{   
    l_FileNames.clear();
    l_Functions.clear();
    l_Plugins.clear();
}   

//**************************************************************************************************
bool PluginLoader::LoadSharedObjects()                      
{
    for_each(l_FileNames.begin(), l_FileNames.end(), *p_LibLoader);
}   

//**************************************************************************************************
void PluginLoader::LoadSharedObject(const std::string sFileName)
{   
    void* pHandle = dlopen(sFileName.c_str(), i_LibMode);
    //if(pHandle == NULL) 
    //Check dlerror
}   

//**************************************************************************************************
void PluginLoader::SetLoadingPolicy(unary_function<const string, void>*& pPolicy)
{
    if(pPolicy != NULL)                                     
    {                                                       
        delete p_LibLoader;
        p_LibLoader = pPolicy;
    }
}

我猜现在没关系。

4 个答案:

答案 0 :(得分:4)

这是一种更简单的方法:

void Print(int x)
{
    cout << x << endl;
}

class X
{
    public:
        void Do()
        {
            int arr[] = {1, 2, 3, 4, 5};
            for_each(arr, arr+5, Print);
        }
};

或许,如果你需要它来存储状态,可以将Print重新定义为仿函数:

struct Print {
    void operator()(int x)
    {
        cout << x << endl;
    }
};

class X
{
    public:
        void Do()
        {
            int arr[] = {1, 2, 3, 4, 5};
            for_each(arr, arr+5, Print());
        }
};

这样可以省去你所看到的所有icky绑定。 (这也给你一个更苗条的课程,这通常是一件好事)

虽然在这种特殊情况下,一种更自然的方式实际上可能是完全抛弃for_each而只是copy输出流:

int arr[] = {1, 2, 3, 4, 5};
std::copy(arr, arr+5, std::ostream_iterator<int>(std::cout));

关于STL的好处是你拥有各种算法,而不仅仅是for_each。您可以根据需要复制,转换(映射),累积(折叠/缩小)或许多其他算法。在这种情况下,您要做的是将数组的内容复制到流中,并且可以将流打扮成迭代器,从而允许std::copy工作。

答案 1 :(得分:2)

我得到了它的工作:D。

#include <iostream>
#include <algorithm>
#include <functional>

using namespace std;

class X
{
    public:
        void Print(int x)
        {
            cout << x << endl;
        }

        void Do()
        {
            int arr[] = {1, 2, 3, 4, 5};
            mem_fun1_t<void, X, int> m(&X::Print);
            binder1st<mem_fun1_t<void, X, int> > b(m, this);
            for_each(arr, arr+5, b);
        }
};

int main()
{
    X x;
    x.Do();
}

答案 2 :(得分:1)

你需要:

#include <functional>

代码。

编辑:请参阅Billy ONeil关于解决此问题后该怎么做的答案。

答案 3 :(得分:-4)

试试这个,

#include <iostream.h>
#include <algorithm.h>