调用模板函数时的C ++模板推导

时间:2011-10-18 16:37:44

标签: c++ templates template-deduction

FastDelegate是指http://www.codeproject.com/KB/cpp/FastDelegate.aspx,但我认为它不相关。

我的代码如下,并且出错。

#include <FastDelegate.h>


using namespace fastdelegate;

template <typename T>
T Getter() {}

template <typename T>
void Setter(T) {}

template <typename T>
class Prop
{
public:
    typedef FastDelegate0<T> Getter;
    typedef FastDelegate1<T> Setter;

    Prop(Getter getter, Setter setter) :
        m_Getter(getter), m_Setter(setter)
    {

    }

private:
    Getter m_Getter;
    Setter m_Setter;
};

template <typename T>
inline Prop<T>* MakeProp(FastDelegate0<T> getter, FastDelegate1<T> setter)
{
    return new Prop<T>(getter, setter);
}

static int Target = 0;
int main()
{
    FastDelegate0<int> fdGetter(Getter<int>);
    Prop<int>* c = MakeProp(fdGetter, Setter<int>);
    // ^^^^ error: no matching function for call to 'MakeProp'
}

如果将main()更改为:

int main()
{
    FastDelegate0<int> fdGetter(Getter<int>);
    FastDelegate1<int> fdSetter(Setter<int>);
    Prop<int>* c = MakeProp(fdGetter, fdSetter); // It works.
}

或:

int main()
{
    FastDelegate0<int> fdGetter(Getter<int>);
    Prop<int>* c = MakeProp<int>(fdGetter, Setter<int>); // It works, too.
}

我认为,MakeProp()应该从fdGetter(T获取int,而不是自动调用FastDelegate1<int>的构造函数。但它没有。为什么?< / p>

P.S。我想在Prop中保存getter和setter,欢迎任何有关此方法的建议。也许在函数中传递参数期间复制FastDelegate *的实例是不好的。

1 个答案:

答案 0 :(得分:0)

你试过吗

Prop<int>* c = MakeProp(FastDelegate0<int>(Getter<int>), FastDelegate1<int>(Setter<int>));

Setter<int>无法转换为FastDelegate1<T>