返回类型 T 的函数模板无法编译
以下代码可以正常编译:
template<typename T>
void f(const T &item) { return; }
int main()
{
f("const string literal");
}
Compilation success at ideone : http://ideone.com/dR6iZ
但是当我提到返回类型,它无法编译:
template<typename T>
T f(const T &item) { return item; }
int main()
{
f("const string literal");
}
现在它给出错误:
prog.cpp:6: 错误:没有匹配的函数可用于调用“f(const char [21])”
ideone 处的代码: http ://ideone.com/b9aSb
即使我将返回类型设为const T,它也会无法编译。
我的问题是:
- 为什么它不能编译?
- 返回类型与错误和函数模板实例化有什么关系?
The following code compiles fine:
template<typename T>
void f(const T &item) { return; }
int main()
{
f("const string literal");
}
Compilation succeeded at ideone : http://ideone.com/dR6iZ
But when I mention the return type, it doesn't compile:
template<typename T>
T f(const T &item) { return item; }
int main()
{
f("const string literal");
}
Now it gives error:
prog.cpp:6: error: no matching function for call to ‘f(const char [21])’
Code at ideone : http://ideone.com/b9aSb
Even if I make the return type const T
, it doesn't compile.
My question is :
- Why does it not compile?
- What does the return type has to do with the error and the function template instantiation?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您无法从函数返回数组,因此模板实例化失败,并且没有匹配的函数。
您收到此特定错误是因为 SFINAE - 编译器无法实例化您的函数并不是真正的错误,这是一个没有匹配函数的错误。
您可以返回对数组的引用 - 返回
T const &
就可以了。编辑:回应评论:
首先,这实际上是 SFINAE 的一个不错的例子。
当编译器编译它时,它首先尝试实例化模板化的 f,为类型
const char [3]
创建完全匹配。由于上述原因,此操作失败了。然后,它会选择不精确匹配、普通函数,并在调用中将const char [3]
衰减为const char *
。You cannot return an array from a function, so template instantiation fails, and there's no matching function.
You get this particular error because of SFINAE - It's not really an error that the compiler cannot instantiate your function, it is an error that there's no matching function.
You can return a reference to an array - returning
T const &
will work.EDIT: In response to comments:
First, this is actually a decent example of SFINAE.
When the compiler compiles this, it'll first try to instantiate the templated f, to create an exact match for the type
const char [3]
. This fails, because of the mentioned reasons. It'll then select the inexact match, the plain function, and in the call decay theconst char [3]
to aconst char *
.看起来好像你告诉它你计划返回一个 T,但实际上你返回了一个 const T&。也许尝试将声明更改为:
或者将返回值更改为参数的取消引用版本:
it looks as though you tell it that you plan on returning a T, but then you actually return a const T&. maybe try changing the declaration to:
or maybe change the return value to a dereferenced version of the argument: