因此,对于我当前正在从事的项目,我试图创建一种“函数查找表”,基本上是字符串到函数的映射。该函数接收数据,对其进行修改,然后将其吐出。但是,似乎std :: function不可能返回任何东西。
我尝试做的(对std :: function不太了解)只是这样写;
import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
import { Button, Pagination } from "antd";
import "antd/dist/antd.css";
import "./index.css";
const apiProducts = [
{ id: 1, name: "item 1" },
{ id: 2, name: "item 2" },
{ id: 3, name: "item 3" },
{ id: 4, name: "item 4" },
{ id: 5, name: "item 5" },
{ id: 6, name: "item 6" }
];
const App = () => {
const [currentPage, setCurrentPage] = useState(1);
const [products, setProducts] = useState([]);
useEffect(() => {
const fetchProduct = async id => {
setProducts(apiProducts[id - 1]);
};
fetchProduct(currentPage);
}, [currentPage]);
const handleChange = (page, pageSize) => {
setProducts(apiProducts[currentPage - 1]);
};
const doClick = e => {
const newPage = currentPage + 1 === 7 ? 1 : currentPage + 1;
setCurrentPage(newPage);
};
return (
<div className="App">
<div style={{ marginTop: "16px" }}>
<Button type="primary" onClick={doClick}>
Next Product Page
</Button>
<Pagination
current={currentPage}
pageSize={1}
total={6}
onChange={handleChange}
/>
</div>
<div style={{ marginTop: 40 }}>Current Product: {products.name}</div>
</div>
);
};
ReactDOM.render(<App />, document.getElementById("root"));
或更具体地说,
map<string, function<Array(vector<pair<char, string>>)>>
(数组是我自己的类,但是其他所有内容都在std中)
如果我写的没有回报;
function<Array(vector<pair<char, string>>)>
它工作正常。
gcc给出的错误是;
function<void(vector<pair<char, string>>)>
有什么方法可以使用std :: function或任何类似方法返回值,还是我完全误解了这一点?
编辑: 这是问题中涉及的代码 主班(缩短,可能会有更多包含):
no matching constructor for initialization of 'map<std::__1::string, function<Array (vector<pair<char, std::__1::string> >)> >'
数组类标题:
#include <iostream>
#include <map>
#include <array>
#include <fstream>
#include <algorithm>
#include <vector>
#include <functional>
#include "Array.h"
using namespace std;
int main() {
map<string, function<Array(vector<pair<char, string>>)>> dictionary =
{
{
"JMP",
[](vector<pair<char, string>> operands) {
if (operands.size() == 1) {
char data[2];
switch (operands[0].first) {
case 3:
data[1] = static_cast<char>(bitset<8>(operands[0].second.substr(1, 2)).to_ulong());
break;
case 4:
data[1] = static_cast<char>(bitset<8>(operands[0].second.substr(2, 8)).to_ulong());
break;
case 5:
data[1] = static_cast<char>(bitset<8>(operands[0].second.substr(2, 8)).to_ulong());
break;
default:
exit(0);
}
data[0] = 0b00000001;
return Array(data, 2);
}
else {
exit(2);
}
}
},
{
"MOV",
[](vector<pair<char, string>> operands) {
return nullptr;
}
}
};
return 0;
}
数组类来源:
#ifndef ARRAY_H_
#define ARRAY_H_
struct Array {
public:
Array();
Array(char* data, int size);
virtual ~Array();
char* data;
int size;
};
#endif /* ARRAY_H_ */
答案 0 :(得分:2)
您的问题是您的函数返回的是Array类型的对象,而不是指向它的指针。因此,返回nullptr显然会导致编译错误。尝试返回一个空数组。
{
"MOV",
[](vector<pair<char, string>> operands) {
return Array();
}
}