微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

模板类型推导和类型特征

如何解决模板类型推导和类型特征

我不明白为什么下面的代码不能编译。在重载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 举报,一经查实,本站将立刻删除。