没有 <> 的函数模板存在问题
无论如何,我可以在不写 func2
的情况下做到这一点吗?
int func() { return 5; }
template<class T>
T func2() { return func(); }
int main()
{
auto k = func2();
//auto k = func2<int>();
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
不可以,因为无法推导模板参数。您需要指定它,否则编译器怎么知道用什么来替换它?
int
?双
?用户定义的类型?编辑
如果您已经在使用 C++0x(我认为是因为
auto
),您可以使用新的尾随返回类型函数样式:decltype(func())
将获得func
的返回类型,而不实际调用它。编辑2
好的,您甚至不需要尾随返回类型,简单的
decltype
也能完成这项工作:尾随返回类型对于返回依赖于部分或全部参数的情况更有用,并且特别是如果它们是模板化的。请参阅此处了解详细说明。
No, because the template argument can not be deduced. You need to specify it, how else would the compiler know what to substitute it with?
int
?double
? A user-defined type?Edit
If you're already using C++0x (I assume so because of
auto
), you can use the new trailing return type function style:decltype(func())
would get the return type offunc
, without actually calling it.Edit2
Okay, you don't even need the trailing return type, a simple
decltype
does the job too:The trailing return type is more useful for situations where the return depends on some or all of the parameters, and especially if they're templated. See here for a nice explanation.
也许您正在寻找类似的东西:
但是,我不明白为什么您将
func2
设为模板,因为您总是希望它返回int
。如果您想将 func 的结果转换为另一种类型,它可能很有用,但在这种情况下,您需要明确指定您想要作为返回的类型。Perhaps you are looking for something like that:
However, I don't understand why you made
func2
a template, since you always want it to return anint
. It could be useful if you wanted to cast the result offunc
to another type, but in this case you would need to specify explicitely the type you want as a return.不,没有办法做到这一点。编译器无法推导模板参数,因为它不考虑其返回类型。
如果您愿意宽容并使用
int k
而不是auto k
那么您可以使用“作弊”通过返回具有隐式代理对象来实现相同的目标转换为类型名T
。No, there is no way to do this. The compiler has no way of deducing the template argument since it does not consider the return type for that.
If you are willing to relent and use
int k
instead ofauto k
then you can use a “cheat” to achieve the same goal by returning a proxy object that has an implicit conversion to typenameT
.编译器无法从您分配给的返回类型推断出模板参数类型。您没有向编译器给出任何提示,返回类型可能是什么。因此,任何无法推导的模板参数类型都需要显式指定。
The compiler is not able to deduce the template argument type from the return type you are assigning to. You are not giving any hint to the compiler what the return type could be. Therefore, any template argument types which cannot be deduced need to be explicitly specified.
您可以使用 c++03 实现此语法如果您使用
int
而不是auto
:编辑:nvm,
Konrad Rudolph 的答案已经说过了。
You can achieve this syntax with c++03 if you use
int
instead ofauto
:EDIT: nvm,
Konrad Rudolph
's answer already said this.