小编mar*_*rco的帖子

C++ call function with many different types

I have an overloaded function that I have to call with many different types. The simple approach is:

uint8_t a;
uint16_t b;
//....
double x;

doSomething(a);
doSomething(b);
//...
doSomething(x);
Run Code Online (Sandbox Code Playgroud)

expressing those calls succinctly can be done with a variadic template as explained at this Q&A. The code will look somewhat like this:

auto doSomethingForAllTypes = [](auto&&... args) {
    (doSomething(args), ...);
};

uint8_t a;
uint16_t b;
//....
double x;

doSomethingForAllTypes(a, b, ... ,x);
Run Code Online (Sandbox Code Playgroud)

But I'll have to do this at …

c++ containers templates variadic

11
推荐指数
3
解决办法
994
查看次数

如何将变量的名称作为变量传递

如何将我想要更改的变量设置为函数参数?我想只定义一个函数,而不是set_a(value),set_b(value),set_c(value),...

class MyVarClass:
    def __init__(self):
        self.a = 1
        self.b = 2
        self.c = 3

# this works, but I don't want to write n functions
def set_a(myvar_object, value):
    myvar_object.a = value

# this is what I actually want:
def set_vars(myvar_object, var_name, value):
    myvar_object.var_name = value

myvar = MyVarClass()
# I want to do the same as  myvar.a = 4
set_a(myvar, 4) # works as intended, now myvar.a is 4
set_vars(myvar, a, 4)  # error, a is not defined
Run Code Online (Sandbox Code Playgroud)

python

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

标签 统计

c++ ×1

containers ×1

python ×1

templates ×1

variadic ×1