Ran*_*its 8 c++ lambda templates c++17
以下代码片段(在OS X上使用gcc 6.3.0使用-std = c ++ 17编译)演示了我的难题:
#include <experimental/tuple>
template <class... Ts>
auto p(Ts... args) {
return (... * args);
}
int main() {
auto q = [](auto... args) {
return (... * args);
};
p(1,2,3,4); // == 24
q(1,2,3,4); // == 24
auto tup = std::make_tuple(1,2,3,4);
std::experimental::apply(q, tup); // == 24
std::experimental::apply(p, tup); // error: no matching function for call to 'apply(<unresolved overloaded function type>, std::tuple<int, int, int, int>&)'
}
Run Code Online (Sandbox Code Playgroud)
为什么可以成功应用推断对lambda的调用而不是对模板函数的调用?这是预期的行为,如果是,为什么?
两者之间的区别在于,它p是一个函数模板,而q泛型lambda是一个带有模板化调用操作符的闭包类。
尽管上述调用运算符的定义与定义几乎相同p,但是闭包类根本不是模板,因此,它不保留的模板参数解析方式std::experimental::apply。
这可以通过定义p为仿函数类来检查:
struct p
{
auto operator()(auto... args)
{ return (... * args); }
};
Run Code Online (Sandbox Code Playgroud)