【发布时间】:2014-10-23 03:30:04
【问题描述】:
我见过这个问题的变体,但它们通常涉及返回相同类型的函数。这是我的代码:
#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) 函数最终会被调用两次,因为我的地图认为它的所有函数都返回浮点数。
有什么好办法吗?这是一个很好的做法吗?我找到了一个不同的解决方案,但我认为如果这样的事情是合法的,它可能会很性感。
【问题讨论】:
-
考虑:
string s = "int"; checkType(myMap[s]());你要这个打电话给checkType(int)吗?我不明白这是怎么回事。调用哪个重载完全在编译时确定 - 它不可能在运行时根据字符串变量恰好具有的值而改变。 -
嗯,float 函数不应该被调用两次。您应该会遇到编译失败。
-
@LightnessRacesinOrbit 即使返回类型不是函数签名的一部分?
-
@BЈовић 函数的签名无关;该程序显然调用了
getInt,然后调用了getFloat,那么为什么getFloat被调用了两次呢? -
@LightnessRacesinOrbit 很奇怪。我编译了,
getFloat()没有被调用两次。checkType(float x)被调用了两次。
标签: c++ function c++11 map overloading