在Visual Studio 2008中,编译器无法解析下面SetCustomer
中对_tmain
的调用并使其明确无误:
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
。为什么不呢?
我可以通过将Producer
更改为
template <typename TConsumer>
struct Producer
{
template <typename TConsumer2>
void SetConsumer(TConsumer2* consumer) { consumer_ = consumer; }
TConsumer* consumer_;
};
并将SetConsumer
称为
producer.SetConsumer<AppleConsumer>(&consumer); // Unambiguous call!!
但如果我不必......那就更好了。
答案 0 :(得分:13)
我认为模板参数查找机制足够聪明,可以推断出正确的基本生产者。
这与模板无关,它来自于使用多个基类 - 名称查找已经不明确,只有在此之后才会发生重载解析。
简化示例如下:
struct A { void f() {} };
struct B { void f(int) {} };
struct C : A, B {};
C c;
c.f(1); // ambiguous
变通方法显式限定了调用或将函数引入派生类范围:
struct ShillyShallyProducer : public Producer<AppleConsumer>,
public Producer<MeatConsumer>
{
using Producer<AppleConsumer>::SetConsumer;
using Producer<MeatConsumer >::SetConsumer;
};
答案 1 :(得分:2)
您可以在函数调用中使用显式限定。而不是:
producer.SetConsumer(&consumer);
尝试:
producer.Producer<AppleConsumer>::SetConsumer(&consumer);