如何解决带有可变参数的动态调度函数调用
我有一些函数来支持它们都采用同构参数。但是每个函数可以采用不同数量的函数。 通过指定函数名及其参数来调用这些函数。
示例,
#include <iostream>
#include <vector>
#include <cmath>
enum class operation{
abs,add,ceil,floor,sub
};
template <typename... T>
int foo(operation op,const T&... args){
std::vector<int> operands({args...});
switch(op){
case operation::abs:
return abs(operands[0]);
case operation::add:
return operands[0] + operands[1];
case operation::ceil:
return ceil(operands[0]);
case operation::floor:
return floor(operands[0]);
case operation::sub:
return operands[0] - operands[1];
}
}
int main() {
// operation is a user input at runtime
operation op = operation::add;
// call foo with some arguments
std::cout << foo(op,5,6);
return 0;
}
这有一些问题:
- 使用向量,因此有不必要的堆分配。
- 代码膨胀,因为所有操作都针对不同数量的参数进行编译。
- 一个非常大的 if/else,因为我不断添加操作。
大多数相关问题使用函数对象和模板来解决这个问题。但是这里的操作是未知的编译时常量。
是否有更好的方法来执行此操作,而无需为 foo 的所有实例中的所有操作编译代码?
解决方法
https://godbolt.org/z/aKxsb18qe
class DatabaseService {
final String uid;
DatabaseService({@required this.uid}); //Added the @required annotation here
...
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。