【问题标题】:Resolve ambiguous template解决模棱两可的模板
【发布时间】:2026-01-10 04:55:01
【问题描述】:

我想知道是否可以解决这个模棱两可的模板函数:

//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

【问题讨论】:

  • 使用特化而不是重载
  • 为什么没有两个函数呢?你不能多态地使用它们,而且它们在语义上可能完全不同

标签: c++ templates ambiguous


【解决方案1】:

您可以为void 显式特化模板:

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

【讨论】:

  • 你不能用返回类型来做到这一点,那就是重载
  • @DavidKernin:我不明白你的意思。你可以这样做,它是模板专业化,而不是重载。演示:ideone.com/6N53rW
  • 这是一个不错的解决方案,但是是否可以有 2 个模板参数并且只专门化一种类型?像这样ideone.com/7IYfPp
  • 哦,我也想过同样的事情,但我不知道允许模板特化来更改函数的签名。我今天学到了一些东西..
【解决方案2】:

我不确定我是否明白这一点,但我尝试使用 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  
}

【讨论】:

  • 我承认 Mike Seymour 的回答更接近和更简单地满足您的需求。