[英]Is there any option to defer the evaluation of a function call in a variadic template
Suppose a variadic template: 假设一个可变参数模板:
void f(T value, Args... args)
As one of the arguments a function is passed which returns a value. 作为参数之一,传递一个返回值的函数。
Example: f(1, getName()); 示例:f(1,getName());
Is there a simple way to defer the evaluation of the function, so getName() is invoked inside f() and is not executed if not required. 有没有一种简单的方法可以推迟对函数的求值,因此getName()在f()内部调用,并且在不需要时不执行。
And with a simple way I mean preferably without creating a complex calling syntax. 用一种简单的方式,我的意思是最好不要创建复杂的调用语法。
If you call f like you did in your example there is no way for f to even know that it was passed a function. 如果像在示例中那样调用f,则f甚至无法知道它已被传递给函数。 Only the return value of getName is passed to f.
只有getName的返回值传递给f。
Like so: 像这样:
auto x = getName();
f(1, x);
To only evaluate the function when needed, you can pass a function pointer: 要仅在需要时评估函数,可以传递函数指针:
f(1, getName);
I don't really understand the significance of variadic templates for this problem so I simplified it: 我不太了解可变参数模板对于此问题的重要性,因此我简化了它:
template <typename T, typename F>
void f(T a, F func)
{
if (required)
result = func();
}
If you want to pass arguments that should be used when the function is called, you can use the std::bind facilities or a lambda: 如果要传递在调用函数时应使用的参数,则可以使用std :: bind工具或lambda:
f(1, [&]{ return getName(arg1, arg2); });
Or even a case with arguments from outside and inside f: 甚至是带有f外部和内部参数的情况:
template <typename T, typename F>
void f(T a, F func)
{
if (required)
result = func(3.0f);
}
f(1, [&](float otherArg){ return getName(arg1, arg2, otherArg); });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.