问题描述
我有一些函数来支持它们都采用同构参数。但是每个函数可以采用不同数量的函数。 通过指定函数名及其参数来调用这些函数。
示例,
#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;
}
这有一些问题:
大多数相关问题使用函数对象和模板来解决这个问题。但是这里的操作是未知的编译时常量。
是否有更好的方法来执行此操作,而无需为 foo 的所有实例中的所有操作编译代码?
解决方法
https://godbolt.org/z/aKxsb18qe
class DatabaseService {
final String uid;
DatabaseService({@required this.uid}); //Added the @required annotation here
...
}