我有类似下面的东西,但无法编译它。我不明白为什么当我的变量可以保存不同类型时我不能有不同的类型?
我的代码:
#include <boost/variant.hpp>
#include <iostream>
typedef boost::variant<int, float, double, std::string> MultiType;
int main() {
int a = 1;
std::string b = "b";
bool c = true;
MultiType d = c ? a : b;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
错误:
错误 C2446 ':':没有从 'std::string' 到 'int' 的转换
我想使用字符串值来调用函数。这可能吗?有人可以展示一些实现吗?我会很感激。
class obj {
int num1;
int num2;
}
int func1(obj o) {
return o.num1 + o.num2;
}
// This is an example data set. This map would be populated with values in the map below with some piece of code.
std::map<std::string, std::string> funcNameMap = {{"func1", "func1"}};
int someFunction(std::string funcName, obj o) {
// Get the value associated with the string "funcName" i.e. "func1".
// Calls function "func1" with value "o" and returns the value.
}
int main(){
obj o; …Run Code Online (Sandbox Code Playgroud)