我有以下代碼來演示在另一個函式中呼叫的函式。
下面的代碼作業正常:
#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;
}
住在這里
但是現在我想傳遞一個函式(third)型別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 ;
}
這是完整的代碼(住在這里)以及我是如何做的。
#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;
有人可以告訴我我做錯了什么嗎?我該如何解決?
uj5u.com熱心網友回復:
std::vector<uint8_t> thirds(Number &N): 引數型別是Number&。
因此,您需要 '&' :
std::function<std::vector<uint8_t>(Number&)> myfunc = &thirds;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/537170.html
