c++ - 为什么 gcc 不能为我的函数模板推断出正确的类型?

标签 c++ templates template-argument-deduction

#include <iostream>
#include <functional>
template<typename T>
struct id { typedef T type; };

template<typename T>
void f(T b, typename id<T>::type* a){}

int main() {
   f(0, 0);
}

vs2013:好的!

g++4.8.2:compile error,such is the info:

main.cpp: In function 'int main()':
main.cpp:10:10: error: no matching function for call to 'f(int, int)'
     f(0,0);
          ^
main.cpp:10:10: note: candidate is:
main.cpp:7:6: note: template<class T> void f(T, typename id<T>::type*)
 void f(T b, typename id<T>::type* a){}
      ^
main.cpp:7:6: note:   template argument deduction/substitution failed:
main.cpp:10:10: note:   mismatched types 'typename id<T>::type*' and 'int'
     f(0,0);
          ^

最佳答案

原因是标准一直不清楚具有部分复合类型(例如指针星)的非推导上下文会发生什么,从而使参数不匹配但仍然可以通过隐式转换接受参数

问题 http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1184确实通过添加注释来解决此问题,该注释说明类似于函数参数不包含推导的模板参数的情况,隐式转换也应该被允许以弥补不匹配。

从那时起,在模板参数的参数推导过程中发现了有关处理这些“隐式转换”的其他问题,并由 http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1391 处理。 .

总的来说,我认为 1184 的效果是 GCC 应该接受你的代码,但由于在 #1391 中反射(reflect)的其他情况下的问题,他们可能会推迟实现 #1184,直到确定确切的细节。

关于c++ - 为什么 gcc 不能为我的函数模板推断出正确的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23032032/

相关文章:

c++ - 如何在 C++ 中使用嵌套 vector ?

c++ - 为什么在删除原子引用计数智能指针中的数据之前需要获取屏障?

javascript - 无法将文本绑定(bind)到 VueJS 模板中的 href 属性

c++ - reference_wrapper : make_pair VS Class Template Argument Deduction (CTAD)

c++如何定义需要为其他开发人员调用的常量函数顺序

c++ - ld.exe 找不到 -lcurl

c++ - 模板化重载运算符解析,无隐式转换

C++ 元编程 : overloading of arithmetic operators for types

c++ - 是否保证模板模板参数调用用户提供的推导指南

c++ - 没有尖括号的模板类实例化