Template deduction for function based on its return type?(基于其返回类型的函数模板推导?)
问题描述
我希望能够使用模板推导来实现以下目标:
I'd like to be able to use template deduction to achieve the following:
GCPtr<A> ptr1 = GC::Allocate();
GCPtr<B> ptr2 = GC::Allocate();
而不是(我目前拥有的):
instead of (what I currently have):
GCPtr<A> ptr1 = GC::Allocate<A>();
GCPtr<B> ptr2 = GC::Allocate<B>();
我当前的 Allocate 函数如下所示:
My current Allocate function looks like this:
class GC
{
public:
template <typename T>
static GCPtr<T> Allocate();
};
这能去掉额外的和
吗?
推荐答案
那是不可能的.返回类型不参与类型推导,而是已经匹配了适当的模板签名的结果.不过,您可以将其隐藏在大多数用途中:
That cannot be done. The return type does not take part in type deduction, it is rather a result of having already matched the appropriate template signature. You can, nevertheless, hide it from most uses as:
// helper
template <typename T>
void Allocate( GCPtr<T>& p ) {
p = GC::Allocate<T>();
}
int main()
{
GCPtr<A> p = 0;
Allocate(p);
}
该语法实际上比最初的 GCPtr 好还是差?p = GC::Allocate()
是另一个问题.
Whether that syntax is actually any better or worse than the initial GCPtr<A> p = GC::Allocate<A>()
is another question.
附言c++11 将允许您跳过类型声明之一:
P.S. c++11 will allow you to skip one of the type declarations:
auto p = GC::Allocate<A>(); // p is of type GCPtr<A>
这篇关于基于其返回类型的函数模板推导?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:基于其返回类型的函数模板推导?


基础教程推荐
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- CString 到 char* 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 初始化列表*参数*评估顺序 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09