gpt4 book ai didi

c++ - 重载函数的不同变体可以映射到同一个映射中吗?

转载 作者:行者123 更新时间:2023-12-02 10:04:26 25 4
gpt4 key购买 nike

#include <iostream>
#include <map>
using namespace std;
string read(string a){return "abc";}
void read(float a){}
bool read(int a){return true;}
int main()
{
map<string,string(*)(string)> f1;
map<string,void(*)(float)> f2;
map<string,bool(*)(int)> f3;
f1["read"]=read;
f2["read"]=read;
f3["read"]=read;
string t,u;
while(1)
{
cin>>t>>u;
if(!f1.count(t)||!f2.count(t)||!f3.count(t)) cout<<"Unknown command!\n";
else cout<<f1[t](u);
}
}

这里我想通过它们的键来访问这些重载的函数。但是我如何(或者我可以)将它们全部存储在一张 map 中?像 map<string,/*---*/> f;能够映射具有不同参数类型和不同返回类型的不同函数,以便我可以使用 f["read"]=read;立刻?

最佳答案

您不能将一组重载作为 map 中的一个元素。您可以将一些具有重载成员函数的对象放入映射中,但这也无济于事,因为您希望映射中的元素具有不同的重载。

下一个问题是,当参数来自用户输入时,您需要决定要调用的重载之前 你叫它。通常你让编译器根据参数来决定,但在这里你需要将用户输入解析为参数的类型。

此外, map 中的元素必须全部属于同一类型。该类型应该提供一个接口(interface),允许您以方便的方式调用函数。

换句话说,最简单的方法是将函数包装成始终采用相同参数并始终返回相同参数的东西,然后将其放入映射中。我建议使用 std::istream用于输入和 std::ostream对于输出:

#include <iostream>
#include <map>
#include <functional>
std::string read(std::string a){return "abc";}
void read(float a){}
bool read(int a){return true;}

int main()
{
std::map<std::string,std::function< void(std::istream&,std::ostream&)>> f;
f["read"] = [](std::istream& in,std::ostream& out){
std::string input;
in >> input;
// put logic to decide what overload to call here
bool call_string = true;
bool call_int = false;
bool call_bool = false;
if (call_string) {
out << read("foo");
} else if (call_int) {
out << read(42);
} else if (call_bool) {
//note : read(bool) returns void
read(false);
};

// use the map:
std::string t;
std::cin >> t;
f[t](std::cin,std::cout);
}

对于输入“read 42”,输出为
abc

Live Example

PS:我不会坚持重载解析可以通过推断要放入映射中的函数的参数和返回类型在某种程度上自动化,尽管它不适用于重载(并且将是一个不同的问题)。

关于c++ - 重载函数的不同变体可以映射到同一个映射中吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60959336/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com