解析歧义模板

Resolve ambiguous template

本文关键字:歧义      更新时间:2023-10-16

我想知道是否有可能解决这个模糊的模板函数:

//function1
template<typename returnType>
returnType call()
{
    //function with return type
}
//function2
template<typename var>
void call()
{
    //function without return type  
}
call<int>();  //call function1
call<void>(); //call function2 

我想防止以下解决方案:

    //function1
template<typename returnType>
returnType call()
{
    //function with return type
}
//function2
void call()
{
    //function without      
}
call<int>();  //call function1
call(); //call function2

您可以显式专门化void的模板:

//function2
template<>
void call<void>()
{
    //function without return type  
}

我不确定我是否明白了这一点,但我尝试了一下SFINAE:

//function1
template<typename returnType>
typename std::enable_if
<
    !std::is_same< returnType, void >::value,
    returnType
>::type call()
{
    //function with return type
}
//function2
template<typename var>
typename std::enable_if
<
    std::is_same< var, void >::value
>::type call()
{
    //function without return type  
}