具有模板参数而非函数参数的Lambda函数 [英] Lambda functions with template parameters, not in function parameters
问题描述
为什么第一次调用无法编译?
Why does the first call not compile?
auto get1 = []<int B>() { return B; };
auto get2 = []<typename B>(B b) { return b; };
int main()
{
get1<5>(); // error: no match for operator<
get2(5); // ok
}
我之所以使用它,是因为它在代码。
The reason I use this, is an expression repeated many times in code.
我当然可以使用真实的函数模板,但是我很好奇。
Of course I can use a real function template, but just I am curious WHY.
推荐答案
如果考虑与 get1
等效的类类型,这将更容易理解:
This is easier to understand if you consider what the equivalent class type looks like to your get1
:
struct get1_t {
template <int B> operator()() const { return B; }
};
get1_t get1;
get1<5>(); // error
您试图为调用运算符提供一个显式的模板参数,但是从语法上讲,正在做为 get1
本身提供模板参数的操作(即,好像 get1
是一个变量模板)。为了为调用运算符提供模板参数,您必须直接执行以下操作:
You're trying to provide an explicit template parameter to the call operator, but syntactically you're doing what looks like providing template parameters for get1
itself (i.e. as if get1
were a variable template). In order to provide the template parameter for the call operator, you have to do that directly:
get1.operator()<5>(); // ok
或重组呼叫运算符以采用可推论的东西:
Or restructure the call operator to take something deducible:
template <int B> struct constant { };
get1(constant<5>{});
或者将整个结构重组为实际的看起来像这样的变量模板:
Or restructure the whole thing to actually be the variable template that it looks like it is:
template <int B>
auto get1 = [] { return B; };
现在, get1< 5>
本身您正在调用的lambda。也就是说,除了具有调用运算符模板的lambda之外,我们还有一个变量模板lambda本身不是模板。
Now, get1<5>
is itself a lambda, that you're invoking. That is, rather than a lambda with a call operator template we have a variable template lambda that is itself not a template.
这篇关于具有模板参数而非函数参数的Lambda函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!