限制可变参数函数中的参数数
Limiting the number of arguments in a variadic function
所以我一直在研究一个函数类,默认情况下,我可以这样做,它可以工作:
int main(){
function f("x^2+1");
cout<<f(3)<<endl;
return 0;
}
"假设正确的包含和命名空间"
无论如何,我希望能够传入多个变量,甚至说明这些变量是什么,就像;
function f("x^2+y^2",x,y); // it doesn't really matter if it's x, 'x', or "x"
cout<<f(3,4)<<endl; // input 3 as x, and 4 as y
我相当确定我可以使用可变参数函数为构造函数找出一些问题,甚至可以正确解决,但是有没有办法强制 operator() 参数恰好接受 2 个值?
我只是在看可变参数函数,因为它们确实是我在 c++ 中看到的第一个可以接受多个参数的东西,所以如果最好以其他方式做到这一点,我完全赞成。
您可以使用 static_assert
来限制可变参数的数量。
template <typename ... Args>
void operator()(Args&&... args)
{
static_assert(sizeof...(Args) <= 2, "Can deal with at most 2 arguments!");
}
或者您可以使用enable_if
template <typename ... Args>
auto operator()(Args&&... args) -> std::enable_if_t<sizeof...(Args) <= 2>
{
}
template<class T>
using double_t=double;
template<class...Ts>
using nfun=std::function<double(double_t<Ts>...)>;
template<class...C>
nfun<C...> func(const char*,C...c);
这将返回一个 n 元std::function
等于要func
的"变量"参数的数量。
因此,func("x^2+y",'x','y','z')
将返回std::function<double(double,double,double)>
作为示例。
相关文章:
- 在函数中使用 const int size 参数创建数组会在 Visual Studio 中抛出错误 C++:表达式的计
- 如何在模板函数中实例化其长度使用模板参数的数组
- 基于参数创建数组
- Pybind11 默认参数 numpy 数组或 None
- 有没有办法根据命令行参数定义数组大小?运行时与编译时实例化?
- 更改为参数的数组的值
- 根据 C++11 中的模板参数选择数组大小
- 是否可以使用C 函数中的const int参数创建数组
- 根据参数将数组分成 5 个不同的数组
- 你究竟如何通过函数的参数传递数组?
- 函数参数中数组大小未指定
- 数组作为函数参数查找数组长度时出错
- 如何使用函数参数设置数组大小
- 可变参数模板数组调用未定义的行为
- 提升 1.55,而 13 信号参数错误数
- 指向作为模板参数的数组的指针
- C++可变参数模板数组/访问元素
- 在 c++ 中没有参数的数组
- 具有双精度参数的数组
- 使用 C++11 的 begin() 和 end() 函数通过参数确定数组维度