нет соответствующей функции для вызова for_each

вот код:

#include <vector>
#include <algorithm>
#include <string>
#include <map>
#include <iostream>
using namespace std;

map<string, int> g_map;
void read_item(const pair<string, int>& p) {
g_map[p.first] += p.second;
}

void myprint(std::pair<const string, int> ci) {
cout << "first : " << ci.first << "seconde : " << ci.second << endl;
}

void myprint(int ci) {
cout << ci << endl;
}

int main()
{
string a = string("nail");
string b = string("hammer");
read_item(make_pair(a, 100));
read_item(make_pair(b, 2));
read_item(make_pair(b, 10));
read_item(make_pair(a, 200));

std::for_each(g_map.begin(), g_map.end(), myprint); // can't find the matching function here
vector<int> vec;
vec.push_back(3);
vec.push_back(3);
std::for_each(vec.begin(), vec.end(), myprint);  // and here
return 0;
}

Я перегружал функцию myprintЯ думаю, что это должно работать, но это не так. когда я меняю первый myprint в myprint1 а второй myprint2, оно работает. любое тело может помочь? ошибка компиляции:

funcTemOverload.cpp: In function 'int main()':
funcTemOverload.cpp:29:54: error: no matching function for call to 'for_each(std::map<std::basic_string<char>, int>::iterator, std::map<std::basic_string<char>, int>::iterator, <unresolved overloaded function type>)'
funcTemOverload.cpp:29:54: note: candidate is:
In file included from d:\mingw\bin\../lib/gcc/x86_64-w64-mingw32/4.7.2/include/c++/algorithm:63:0,
from funcTemOverload.cpp:2:
d:\mingw\bin\../lib/gcc/x86_64-w64-mingw32/4.7.2/include/c++/bits/stl_algo.h:4436:5: note: template<class _IIter, class _Funct> _Funct std::for_each(_IIter, _IIter, _Funct)
d:\mingw\bin\../lib/gcc/x86_64-w64-mingw32/4.7.2/include/c++/bits/stl_algo.h:4436:5: note:   template argument deduction/substitution failed:
funcTemOverload.cpp:29:54: note:   couldn't deduce template parameter '_Funct'
funcTemOverload.cpp:35:50: error: no matching function for call to 'for_each(std::vector<int>::iterator, std::vector<int>::iterator, <unresolved overloaded function type>)'
funcTemOverload.cpp:35:50: note: candidate is:
In file included from d:\mingw\bin\../lib/gcc/x86_64-w64-mingw32/4.7.2/include/c++/algorithm:63:0,
from funcTemOverload.cpp:2:
d:\mingw\bin\../lib/gcc/x86_64-w64-mingw32/4.7.2/include/c++/bits/stl_algo.h:4436:5: note: template<class _IIter, class _Funct> _Funct std::for_each(_IIter, _IIter, _Funct)
d:\mingw\bin\../lib/gcc/x86_64-w64-mingw32/4.7.2/include/c++/bits/stl_algo.h:4436:5: note:   template argument deduction/substitution failed:
funcTemOverload.cpp:35:50: note:   couldn't deduce template parameter '_Funct'

2

Решение

В соответствии с запросом причина, по которой исходный код не работает, заключается в UnaryFunction параметр шаблона std::for_each используется только в «не выводимом контексте» и явно не указан. [temp.deduct.type]/4:

… Если параметр шаблона используется только в не выведенных контекстах и ​​не указан явно, вывод аргумента шаблона завершается неудачно.

UnaryFunction трактуется как не выводимый контекст из-за [temp.deduct.call]/6

Когда P [UnaryFunction] является типом функции, указателем на тип функции или указателем на тип функции-члена … Если аргумент [myprint] является набором перегрузки (не содержащим шаблонов функций), попытка выведения пробного аргумента выполняется с использованием каждого из участники набора. Если вывод выполняется только для одного из членов набора перегрузки, этот элемент используется в качестве значения аргумента для вывода. Если вывод выполняется успешно для более чем одного члена набора перегрузки, параметр обрабатывается как невыгруженный контекст.

Одним из вариантов является добавление приведений:

std::for_each(
g_map.begin(), g_map.end(),
static_cast<void (*)(std::pair<const string, int>)>(myprint));

std::for_each(
vec.begin(), vec.end(),
static_cast<void (*)(int)>(myprint));

Другой вариант — сделать myprint быть функциональным объектом, так что разрешение перегрузки происходит внутри std::for_each:

struct myprint {
void operator()(std::pair<const string, int> ci) const {
cout << "first : " << ci.first << "seconde : " << ci.second << endl;
}
void operator()(int ci) const {
cout << ci << endl;
}
};

std::for_each(g_map.begin(), g_map.end(), myprint());
std::for_each(vec.begin(), vec.end(), myprint());
6

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector