問題描述
我希望能夠使用模板推導來實現以下目標:
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>
這篇關于基于其返回類型的函數模板推導?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!