【发布时间】:2014-03-17 21:13:17
【问题描述】:
如果我尝试在 MSVC 中编译以下代码:
template <typename DELEGATE>
void newButton(DELEGATE *obj, int (DELEGATE::*method)(int))
{
std::function<int(int)> callback = std::bind(
method, obj, std::placeholders::_1);
// ...
}
class Base
{
public:
virtual int test(int f) { return f * f; }
};
class Derived : public Base
{
};
int main()
{
Derived d;
newButton(&d, &Base::test);
}
我得到一个编译器错误:
'void newButton(DELEGATE *,int (__thiscall DELEGATE::* )(int))' :
template parameter 'DELEGATE' is ambiguous
could be 'Base'
or 'Derived'
这是合理的。模板要求 obj 和 method 具有相同的类型,但它们并不完全相同。
但是,如果我用这个模板结构 typedef 替换指向成员函数的声明,它会编译!
template <typename DELEGATE>
struct ButtonAction
{
typedef int (DELEGATE::*Type)(int);
};
template <typename DELEGATE>
void newButton(DELEGATE *obj, typename ButtonAction<DELEGATE>::Type method)
{
std::function<int(int)> callback = std::bind(
method, obj, std::placeholders::_1);
// ...
}
// rest same as before
为什么?我本来希望 typedef 解析为完全相同的指向成员函数的指针类型,并导致相同的模板错误。
【问题讨论】:
标签: c++ templates inheritance typedef