对基类模板成员函数的模棱两可的访问 [英] Ambiguous access to base class template member function
问题描述
在Visual Studio 2008中,编译器无法将对下面 _tmain
中的 SetCustomer
的调用解析为明确的内容:
In Visual Studio 2008, the compiler cannot resolve the call to SetCustomer
in _tmain
below and make it unambiguous:
template <typename TConsumer>
struct Producer
{
void SetConsumer(TConsumer* consumer) { consumer_ = consumer; }
TConsumer* consumer_;
};
struct AppleConsumer
{
};
struct MeatConsumer
{
};
struct ShillyShallyProducer : public Producer<AppleConsumer>,
public Producer<MeatConsumer>
{
};
int _tmain(int argc, _TCHAR* argv[])
{
ShillyShallyProducer producer;
AppleConsumer consumer;
producer.SetConsumer(&consumer); // <--- Ambiguous call!!
return 0;
}
这是编译错误:
// error C2385: ambiguous access of 'SetConsumer'
// could be the 'SetConsumer' in base 'Producer<AppleConsumer>'
// or could be the 'SetConsumer' in base 'Producer<MeatConsumer>'
我认为模板参数查找机制足够聪明,可以推断出正确的基础 Producer
.为什么不呢?
I thought the template argument lookup mechanism would be smart enough to deduce the correct base Producer
. Why isn't it?
我可以通过将 Producer
更改为
template <typename TConsumer>
struct Producer
{
template <typename TConsumer2>
void SetConsumer(TConsumer2* consumer) { consumer_ = consumer; }
TConsumer* consumer_;
};
并以
调用 SetConsumer
producer.SetConsumer<AppleConsumer>(&consumer); // Unambiguous call!!
但是如果我不必...那就更好了.
but it would be nicer if I didn't have to...
推荐答案
我认为模板参数查找机制足够聪明,可以推断出正确的基本Producer.
I thought the template argument lookup mechanism would be smart enough to deduce the correct base Producer.
这与模板无关,它来自使用多个基类-名称查找已经模棱两可,并且仅在此之后才进行重载解析.
This hasn't to do with templates, it comes from using multiple base classes - the name lookup is already ambiguous and overload resolution only takes place after that.
一个简化的示例如下:
struct A { void f() {} };
struct B { void f(int) {} };
struct C : A, B {};
C c;
c.f(1); // ambiguous
变通办法是明确限定调用或将功能引入派生类范围:
Workarounds are explicitly qualifying the call or to introduce the functions into the derived classes scope:
struct ShillyShallyProducer : public Producer<AppleConsumer>,
public Producer<MeatConsumer>
{
using Producer<AppleConsumer>::SetConsumer;
using Producer<MeatConsumer >::SetConsumer;
};
这篇关于对基类模板成员函数的模棱两可的访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!