函数的模板推导基于其返回类型?

Mar*_*lon 27 c++ templates template-argument-deduction

我希望能够使用模板推导来实现以下目标:

GCPtr<A> ptr1 = GC::Allocate();
GCPtr<B> ptr2 = GC::Allocate();
Run Code Online (Sandbox Code Playgroud)

而不是(我现在拥有的):

GCPtr<A> ptr1 = GC::Allocate<A>();
GCPtr<B> ptr2 = GC::Allocate<B>();
Run Code Online (Sandbox Code Playgroud)

我目前的Allocate功能如下所示:

class GC
{
public:
    template <typename T>
    static GCPtr<T> Allocate();
};
Run Code Online (Sandbox Code Playgroud)

这将是可能敲掉多余的<A><B>

Dav*_*eas 31

那是不可能做到的.返回类型不参与类型推导,而是已经匹配了适当的模板签名的结果.但是,您可以将其隐藏在大多数用途中:

// helper
template <typename T>
void Allocate( GCPtr<T>& p ) {
   p = GC::Allocate<T>();
}

int main()
{
   GCPtr<A> p = 0;
   Allocate(p);
}
Run Code Online (Sandbox Code Playgroud)

这种语法实际上是否比最初的更好或更差GCPtr<A> p = GC::Allocate<A>()是另一个问题.

PS c ++ 11将允许您跳过其中一个类型声明:

auto p = GC::Allocate<A>();   // p is of type GCPtr<A>
Run Code Online (Sandbox Code Playgroud)


Unc*_*ens 27

我唯一能想到的是:make Allocate是一个非模板,它返回一个非模板代理对象,它有一个模板化的转换运算符,可以完成真正的工作:

template <class T>
struct GCPtr
{

};

class Allocator
{
public:
    template <class T>
    operator GCPtr<T>() { return GCPtr<T>(); }
};

class GC
{
public:
    static Allocator Allocate() { return Allocator(); }//could give a call-back pointer?
};

int main()
{
    GCPtr<int> p = GC::Allocate();
}
Run Code Online (Sandbox Code Playgroud)

  • 这似乎有点矫枉过正,但我​​仍然不知道这种模式.你教过我一些东西.所以+1. (3认同)

jal*_*alf 8

你可以走相反的路线.

如果您使用的是最新的编译器(MSVC 2010这应该是出在一两天,或当前版本的GCC),不介意靠的C++ 0x的特点:

auto ptr1 = GC::Allocate<A>();
auto ptr2 = GC::Allocate<B>();
Run Code Online (Sandbox Code Playgroud)

会为您节省额外的<A><B>,只是没有在右手边.:)