gpt4 book ai didi

c++ - 将字符串映射到具有不同返回类型的函数

转载 作者:太空狗 更新时间:2023-10-29 21:42:21 25 4
gpt4 key购买 nike

我见过这个问题的变体,但它们通常涉及返回相同类型的函数。这是我的代码:

#include <iostream>
#include <functional>
#include <map>

using namespace std;

void checkType(int x){
cout << "we got an int: " << x << endl;
}

void checkType(float x){
cout << "we got a float: " << x << endl;
}

int getInt(){
return 1;
}

float getFloat(){
return -101.23f;
}

int main(){
map<string, function<float()> > myMap({
{"int", getInt},
{"float", getFloat}
});

checkType(myMap["int"]());
checkType(myMap["float"]());

return 1;
}

此处的目标是根据映射函数返回的内容调用不同版本的重载函数 (checkType)。显然,checkType(float) 函数最终被调用了两次,因为我的 map 认为它的所有函数都返回 float 。

有什么好的方法吗?这是好的做法吗?我找到了一个不同的解决方案,但我认为如果这样的事情是合法的,它可能会非常性感。

最佳答案

正如您已经发现的那样,您实现它的方式是行不通的,因为存储在 map 中的函数正在返回 float。

正确的方法是使用类型删除,但如果使用 void*,则必须注意正确的转换。另一种选择是使用 boost::anyQVariant

此示例使用 const void* 来删除类型:

#include <iostream>
#include <functional>
#include <map>

using namespace std;

void callForInt(const void* x){
const int* realX = static_cast < const int* >( x );
cout << "we got an int: " << *realX << endl;
}

void callForFloat(const void* x){
const float* realX = static_cast < const float* >( x );
cout << "we got a float: " << *realX << endl;
}

int main(){
map<string, function<void(const void*)> > myMap({
{"int", callForInt},
{"float", callForFloat}
});

const int v1 = 1;
const float v2 = -101.23f;

myMap["int"](&v1);
myMap["float"](&v2);
}

关于c++ - 将字符串映射到具有不同返回类型的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26520835/

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