Bar*_*rry 9 c++ templates c++11 template-argument-deduction
考虑这个简单(坏)函数模板,该站点上存在许多变体:
template <typename R, typename... Args>
R call_with(std::function<R(Args...)> f,
Args... args)
{
return f(args...);
}
Run Code Online (Sandbox Code Playgroud)
两次尝试称它为:
call_with([]{}); // (a)
call_with<void>([]{}); // (b)
Run Code Online (Sandbox Code Playgroud)
我不能打电话,(a)因为lambda不是std::function<R(Args...)>这样的模板演绎失败.直截了当.
但是,(b)也失败了.我怀疑这是因为编译器无法确定我的意思是提供我所提供的所有类型参数和原因R- 因此它正在尝试(并且失败)推断出Args...初始调用失败的相同原因.
有没有办法明确指定我提供所有模板参数?为了澄清,我只对如何显式提供模板参数感兴趣,以便没有模板推导 - 我不是在寻找正确的编写方式,call_with也不是在使用lambda调用时使模板推导成功的方法.
对你编辑的问题的简短回答是:如果你不能改变声明call_with(),那么要么使用@CoffeeandCode演示的类型转换,要么使用下面描述的技术来创建一个包装器call_with().
问题在于编译器试图从第一个函数参数中推导出模板参数.您可以防止这一点,如果你写你的代码,像这样:
#include <functional>
#include <iostream>
// identity is a useful meta-function to have around.
// There is no std::identity, alas.
template< typename T>
struct identity
{
using type = T;
};
template <typename R, typename... Args>
R call_with( typename identity<std::function<R(Args...)>>::type f,
Args... args)
{
return f(args...);
}
int main()
{
call_with<void>([](int){ std::cout << "called" << std::endl; }, 2);
}
Run Code Online (Sandbox Code Playgroud)
使用模板元函数"生成"std :: function类型意味着编译器甚至不能尝试从第一个参数推导出函数类型,它只会使用其他参数.
您仍然需要显式提供返回类型,但是对于其他参数,您现在可以选择是显式指定它们还是将其留给编译器从给定的参数中推导出它们.
如果您确实希望强制提供所有模板参数而不是推导出,那么您也可以通过identity以下方式调用参数包:
template <typename R, typename... Args>
R call_with( typename identity<std::function<R(Args...)>>::type f,
typename identity<Args>::type... args)
Run Code Online (Sandbox Code Playgroud)
总之,如果要阻止编译器推导出也作为函数参数出现的函数模板参数类型,请将它们包装在元函数中,例如identity.