Ich versuche, eine ANSI C++ for_each-Anweisung zu verwenden, um die Elemente eines Standardvektors zu durchlaufen und zu drucken. Es funktioniert, wenn ich den for_each Aufruf eine nicht überladene Funktion habe, aber einen Compiler-Fehler ergibt, wenn ich es eine überladene Funktion nennen lasse.g ++ - Compilerfehler: Vorlageparameter '_Func' kann nicht abgeleitet werden
Hier ist ein minimal-Testprogramm zu zeigen, wo der Compiler-Fehler auftritt:
#include <algorithm>
#include <iostream>
#include <vector>
struct S {
char c;
int i;
};
std::vector<S> v;
void print_struct(int idx);
void print_struct(const struct S& s);
// f: a non-overloaded version of the preceding function.
void f(const struct S& s);
int main()
{
v.push_back((struct S){'a', 1});
v.push_back((struct S){'b', 2});
v.push_back((struct S){'c', 3});
for (unsigned int i = 0; i < v.size(); ++i)
print_struct(i);
/* ERROR! */
std::for_each(v.begin(), v.end(), print_struct);
/* WORKAROUND: */
std::for_each(v.begin(), v.end(), f);
return 0;
}
// print_struct: Print a struct by its index in vector v.
void print_struct(int idx)
{
std::cout << v[idx].c << ',' << v[idx].i << '\n';
}
// print_struct: Print a struct by reference.
void print_struct(const struct S& s)
{
std::cout << s.c << ',' << s.i << '\n';
}
// f: a non-overloaded version of the preceding function.
void f(const struct S& s)
{
std::cout << s.c << ',' << s.i << '\n';
}
ich die 12.2 in openSUSE kompiliert werden:
g++-4.7 -ansi -Wall for_each.cpp -o for_each
Die vollständige Fehlermeldung lautet:
for_each.cpp: In function ‘int main()’:
for_each.cpp:31:48: error: no matching function for call to ‘for_each(std::vector<S>::iterator, std::vector<S>::iterator, <unresolved overloaded function type>)’
for_each.cpp:31:48: note: candidate is:
In file included from /usr/include/c++/4.7/algorithm:63:0,
from for_each.cpp:5:
/usr/include/c++/4.7/bits/stl_algo.h:4436:5: note: template<class _IIter, class _Funct> _Funct std::for_each(_IIter, _IIter, _Funct)
/usr/include/c++/4.7/bits/stl_algo.h:4436:5: note: template argument deduction/substitution failed:
for_each.cpp:31:48: note: couldn't deduce template parameter ‘_Funct’
Ich sehe keine Suchergebnisse für diesen bestimmten Fehler auf Stack Overflow oder im Web ge nerally. Jede Hilfe wäre willkommen.
http://ideone.com/nqL3x – BoBTFish