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 …
如何将我想要更改的变量设置为函数参数?我想只定义一个函数,而不是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)