Resolve overload ambiguity with SFINAE

落爺英雄遲暮 提交于 2019-12-06 11:17:04

Unfortunately not; SFINAE can be used for selecting between different function template definitions, but not between function overloads passed as an argument.

This is because an overloaded function passed as an argument must be resolved to a single overload before dependent types in the template function definition are evaluated and SFINAE kicks in.

You can see this by creating n overloaded template definitions, where n - 1 is the maximum number of arguments you want to handle:

template < typename R, typename... Args >
typename std::enable_if< 0 == sizeof...( Args ), R >::type
call_my_function( R(*func)(), Args ...a )
{
    return func( a... );
}

template < typename R, typename A1, typename... Args >
typename std::enable_if< 1 == sizeof...( Args ), R >::type
call_my_function( R(*func)(A1), Args ...a )
{
    return func( a... );
}

template < typename R, typename A1, typename A2, typename... Args >
typename std::enable_if< 2 == sizeof...( Args ), R >::type
call_my_function( R(*func)(A1, A2), Args ...a )
{
    return func( a... );
}

Here each arg_count resolves to exactly one call_my_function definition, so there is no ambiguity within a particular call_my_function definition as to which arg_count was passed.

A possible solution would be to generate these n overloads either manually or using the preprocessor (e.g. using Boost.Preprocessor).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!