模板类型推导和类型特征

问题描述

我不明白为什么下面的代码不能编译。在重载1中,推导出的类型是int &,所以应该导致SFINAE。而且我们应该只有一个候选函数

#include <iostream>
#include <type_traits>

template <typename T>
std::enable_if<std::is_same<T,std::remove_reference_t<T>>::value,void> foo(T&& a){
  std::cout << "overload 1" << std::endl;
}

template <typename T>
void foo(T&& a){
  std::cout << std::is_same<T,std::remove_reference_t<T>>::value << std::endl;
  std::cout << "overload 2" << std::endl;
}

int main(){
  int a = 2;
  foo(a);
  // std::cout << std::is_same<int,int&>::value << std::endl;  ---> gives false
  return 0;
}

编译错误

template_with_reference.cpp: In function ‘int main()’:
template_with_reference.cpp:19:8: error: call of overloaded ‘foo(int&)’ is ambiguous
   foo(a);
        ^
template_with_reference.cpp:5:74: note: candidate: std::enable_if<std::is_same<T,typename std::remove_reference< <template-parameter-1-1> >::type>::value,void> foo(T&&) [with T = int&; typename std::remove_reference< <template-parameter-1-1> >::type = int]
 std::enable_if<std::is_same<T,void> foo(T&& a){
                                                                          ^~~
template_with_reference.cpp:11:6: note: candidate: void foo(T&&) [with T = int&]

你们能帮我找出错误吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)