У меня есть следующий код, чтобы продемонстрировать, что функция вызывается внутри другой функции.
Код ниже работает правильно:
#include <iostream>
#include <functional>
int thirds(int a)
{
return a + 1;
}
template <typename T, typename B , typename L>
//------------------------------------------------VVVVV-
int hello(T x, B y, L func)
{
int first = x + 1;
int second = y + 1;
int third = func(6);
return first + second + third;
}
int add()
{
std::function<int(int)> myfunc = thirds;
return hello(1, 1, myfunc); // pass thirds function from here
}
int main()
{
std::cout << add();
return 0;
}
Жить Здесь
Но теперь я хочу передать функцию (третьи) типа Number
(класс C++) с возвращаемым типом std::vector<uint8_t>
функция третей
std::vector<uint8_t> thirds(Number &N)
{
std::vector<uint8_t> z;
z.push_back(N.z);
return z ;
}
Вот полный код ( Live здесь ) и как я это делаю.
#include <stdio.h>
#include <iostream>
#include <functional>
class Number{
public:
int z = 5;
};
std::vector<uint8_t> thirds(Number &N)
{
std::vector<uint8_t> z;
z.push_back(N.z);
return z ;
}
template <typename T, typename B , typename L>
//------------------------------------------------VVVVV-
int hello(T x, B y, L func)
{
int first = x + 1;
int second = y + 1;
Number N;
std::vector<uint8_t> third = func(N);
return first + second ;
}
int add()
{
std::function<std::vector<uint8_t>(Number)> myfunc = &thirds;
return hello(1, 1, myfunc);
}
int main()
{
std::cout << add();
return 0;
}
Я получаю сообщение об ошибке:
error: conversion from ‘std::vector (*)(Number&)’ to non-scalar type ‘std::function(Number)>’ requested
std::function<std::vector<uint8_t>(Number)> myfunc = &thirds;
Может кто-нибудь показать мне, что я делаю неправильно? Как я могу это решить?
std::vector<uint8_t> thirds(Number &N)
: тип аргумента Number&
.
Поэтому вам нужен '&' :
std::function<std::vector<uint8_t>(Number&)> myfunc = &thirds;
auto
сможет подобрать это?
Я не знаю, как быть с auto
, но в этом примере я думаю, что это может быть просто return hello(1, 1, thirds);
.
@ник Ты можешь сделать auto myfunc = std::bind_front(thirds)
или auto myfunc = std::bind(thirds, std::placeholder::_1)
У вас разные сигнатуры функций.
std::vector<uint8_t>(Number)
в одном случае иstd::vector<uint8_t>(Number&)
в другом.