看这个(简化的)例子:
int foo(int) { return 0;}
double foo(double) { return 0.0; }
template <class T>
enable_if<is_integral<T>::value>
bar(T(*f)(T)) {}
int main()
{
bar(foo);
return 0;
}
我的期望是,编译器将首先尝试为每个重载实例化模板,第二个重载将失败(SFINAE),因此void bar(int(*f)(int)
,候选集中将只剩下候选者,这将使用的第一个重载来解决foo
。那不是什么。失败的原因是这样的:
no matching function for call to ‘bar(<unresolved overloaded function type>)’
couldn't deduce template parameter ‘T’
有什么办法可以实现这样的目标吗?
C ++的类型推导非常简单。[temp.deduct.call] /6.2和[over.over] / 1子句描述了将重载名称用作参数的方式。
在您的示例中,两个推论都将成功(到T=int
和T=double
),一次替代将失败。但是语言只要求成功演绎一次。
您问如何实现它。以下是一些选项:
#2的示例:
tempate<class T> struct integral_wrapper { T t; }
integral_wrapper<int> foo(int);
double foo(double);
template<class T>
void bar(integral_wrapper<T> foo(T));
#3的示例:
template<class T>
void bar(T (*f)(T), T);
bar(foo, 0);
#4的示例:
struct foo_t
{
int operator()(int);
double operator()(double);
} foo;
template<class F>
void bar(F);
bar(foo);
请注意,通用Lambda可能是#4的另一种方法。
根据您的使用情况,其中一些可能比其他更具吸引力。将参数传递给STL算法时,方法4特别有用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句