Я столкнулся с некоторыми трудностями при использовании преобразования функции-члена в std::function
с помощью std::bind
. Я использую g++ 7.3.0 и -std=c++11
, и компилятор сообщает:
../untitled2/main.cpp:25:42: error: no match for call to ‘(a) (std::_Bindres_helper<short int, short int (b::*)(), b>::type, int16_t*)’
a0(std::bind<int16_t>(&b::run, b()), &r);
^
../untitled2/main.cpp:7:8: note: candidate: template<class t_result> void a::operator()(std::function<t_result()>&&, t_result*)
void operator()(std::function<t_result()>&& p_function, t_result* p_result)
^~~~~~~~
../untitled2/main.cpp:7:8: note: template argument deduction/substitution failed:
../untitled2/main.cpp:25:42: note: ‘std::_Bindres_helper<short int, short int (b::*)(), b>::type {aka std::_Bind_result<short int, short int (b::*(b))()>}’ is not derived from ‘std::function<t_result()>’
a0(std::bind<int16_t>(&b::run, b()), &r);
когда он пытается скомпилировать этот код:
1 #include <chrono>
2
3
4 struct a
5 {
6 template<typename t_result>
7 void operator()(std::function<t_result()>&& p_function, t_result* p_result)
8 {
9 *p_result = p_function();
10 }
11 };
12
13 struct b
14 {
15 int16_t run() { return -5; }
16 };
17
18 int
19 main()
20 {
21 a a0;
22
23 int16_t r;
24
25 a0(std::bind<int16_t>(&b::run, b()), &r);
26
27 return 1;
28 }
Но компилятор компилирует этот код:
1 #include <chrono>
2
3
4 struct a
5 {
6 template<typename t_result>
7 void operator()(std::function<t_result()>&& p_function, t_result* p_result)
8 {
9 *p_result = p_function();
10 }
11 };
12
13 struct b
14 {
15 int16_t run() { return -5; }
16 };
17
18 int
19 main()
20 {
21 a a0;
22
23 int16_t r;
24
25 std::function<int16_t()> f = std::bind<int16_t>(&b::run, b());
26
27 a0(std::move(f), &r);
28
29 return 1;
30 }
Итак, почему второй код компилируется, а первый нет, если, насколько мне известно, я передаю a::operator()
один и тот же объект в обоих случаях.
Большое спасибо за ваше время!