Comment utiliser bind1st et bind2nd?

Je voudrais savoir comment utiliser les fonctions de liaison.
Voici l'idée:
J'ai cette fonction qui prend en paramètres:

void print_i(int t, std::string separator)
{
        std::cout << t << separator;
}

Et je voudrais faire:

std::vector<int> elements;
//...
for_each(elements.begin(), elements.end(), std::bind2nd(print_i, '\n'));

Mais il ne fonctionne pas !

Voici ce que j'obtiens:

/usr/include/c++/4.3/backward/binders.h: In instantiation of std::binder2nd<void ()(int, std::string)>’:
main.cpp:72:   instantiated from here
/usr/include/c++/4.3/backward/binders.h:138: error: void ()(int, std::string)’ is not a class, struct, or union type
/usr/include/c++/4.3/backward/binders.h:141: error: void ()(int, std::string)’ is not a class, struct, or union type
/usr/include/c++/4.3/backward/binders.h:145: error: void ()(int, std::string)’ is not a class, struct, or union type
/usr/include/c++/4.3/backward/binders.h:149: error: void ()(int, std::string)’ is not a class, struct, or union type
/usr/include/c++/4.3/backward/binders.h:155: error: void ()(int, std::string)’ is not a class, struct, or union type
/usr/include/c++/4.3/backward/binders.h:140: error: field std::binder2nd<void ()(int, std::string)>::op invalidly declared function type
/usr/include/c++/4.3/backward/binders.h: In function std::binder2nd<_Operation> std::bind2nd(const _Operation&, const _Tp&) [with _Operation = void ()(int, std::string), _Tp = char]’:
main.cpp:72:   instantiated from here
/usr/include/c++/4.3/backward/binders.h:164: error: void ()(int, std::string)’ is not a class, struct, or union type
/usr/include/c++/4.3/bits/stl_algo.h: In function _Funct std::for_each(_IIter, _IIter, _Funct) [with _IIter = __gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >, _Funct = std::binder2nd<void ()(int, std::string)>]’:
main.cpp:72:   instantiated from here
/usr/include/c++/4.3/bits/stl_algo.h:3791: error: no match for call to ‘(std::binder2nd<void ()(int, std::string)>) (int&)’
make: *** [all] Error 1

Je pourrais utiliser foncteur, mais il est plus rapide d'utiliser la liaison.

Merci!

Il n'est pas lié à la question, donc un petit commentaire à la place. La plus courte de code à la sortie d'une gamme est probablement le copiant dans ostream_iterator, par exemple std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, "\n"));.

OriginalL'auteur Arthur | 2009-09-13