【发布时间】:2020-08-01 12:01:57
【问题描述】:
如果我在函数参数列表中不使用 tempate 参数(类型)-> 仅作为返回类型,则没有推论:
template <typename T>
T zero() { return 0; }
int main()
{
int x = zero();
}
给予:
a.cpp:15:18: error: no matching function for call to ‘zero()’
int x = zero();
^
a.cpp:11:3: note: candidate: ‘template<class T> T zero()’
T zero() { return 0; }
^~~~
a.cpp:11:3: note: template argument deduction/substitution failed:
a.cpp:15:18: note: couldn't deduce template parameter ‘T’
int x = zero();
编译的唯一方法,是在尖括号中指定模板类型:
template <typename T>
T zero() { return 0; }
int main()
{
int x = zero<int>();
}
-
所以我的问题是,为什么g++ 可以从模板函数的参数列表中推断出类型,而不能从中推断出来返回类型(编译器在编译
main时也知道这个类型,所以它知道类型)。 -
当模板函数在其参数列表中使用模板类型时,为模板函数提供尖括号中的类型是任意的(因为推论)?因此,作为一个好的做法,我是否应该始终在花括号中提供类型,无论函数如何声明?
第二个问题不太可读。简而言之->无论函数声明如何,我都应该每次都使用foo<T>(arg, ...)(提供类型)吗?即使它可以由编译器推断出来,但我还是会提供类型以进行良好的实践?
【问题讨论】:
-
1.是因为 C++ 是这样定义的。 2. 不是一个明确的问题,你能用更多的描述来改写它吗?
-
当你简单地写
zero();时会发生什么 - 因为你可能总是在调用函数时丢弃它们的值。那么编译器应该如何推断类型呢?是不是应该推导出为void?那么这是一个错误,看起来不是很直观。
标签: c++ templates language-lawyer template-argument-deduction