小编Ane*_*ees的帖子

当 boost 变量可以容纳多种类型时,为什么不能使用不同类型的三元运算符?

我有类似下面的东西,但无法编译它。我不明白为什么当我的变量可以保存不同类型时我不能有不同的类型?

我的代码:

#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' 的转换

c++ boost

2
推荐指数
1
解决办法
444
查看次数

使用 std::string 调用 C++11 中的函数

我想使用字符串值来调用函数。这可能吗?有人可以展示一些实现吗?我会很感激。

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)

c++ linux windows c++11

0
推荐指数
1
解决办法
575
查看次数

标签 统计

c++ ×2

boost ×1

c++11 ×1

linux ×1

windows ×1