[英]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-ary std::function
等于func
的'variable'参数的数量。
所以func("x^2+y",'x','y','z')
将返回std::function<double(double,double,double)>
作为示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.