基于返回类型的函数的模板扣除? [英] Template deduction for function based on its return type?

查看:136
本文介绍了基于返回类型的函数的模板扣除?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要使用模板扣除来实现以下操作:

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();
};

这将有可能击倒额外的< A>和< B>

Would this be possible to knock off the extra < A> and < B>?

感谢

推荐答案

返回类型不参与类型推导,而是已经匹配适当的模板签名的结果。然而,你可以隐藏它从大多数用途:

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 A。 p = GC :: Allocate< A>()是另一个问题。

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>

这篇关于基于返回类型的函数的模板扣除?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆