c++ - 对基类模板成员函数的访问不明确

标签 c++ templates

在 Visual Studio 2008 中,编译器无法解析下面 _tmain 中对 SetCustomer 的调用并使其明确:

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!!

但如果我不必...会更好

最佳答案

I thought the template argument lookup mechanism would be smart enough to deduce the correct base Producer.

这与模板无关,它来自使用多个基类 - 名称查找已经不明确,重载解析仅在此之后发生。

一个简化的例子如下:

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;
 };

关于c++ - 对基类模板成员函数的访问不明确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2713160/

相关文章:

android - 将 OpenCV 轮廓从 JNI C++ 函数传递到 Android 中的 Java

c++ - 适当的模板使用

c++ - 对 Singleton 类的静态成员函数的 undefined reference

c++ - DirectX/C++ : Marching Cubes Indexing

c++ - 将时间输入转换为 float 以启用 C++ 中的数学函数

c++ - 安装 Qt 不工作

c++ - 将 uint64_t 转换为 unsigned char serialized[8]

c++ - 功能模板部分特化的解决方法?

c++ - 继承自非专用模板(共享库)

c++ - 两个模板类互为成员组成