我有一个模板类,它对作为模板参数给出的类执行操作。对于我的一些课程,我想将功能“分组”到一个课程中,以使调用者更容易。实际上,代码看起来像这样(名称已更改):
template<typename T>
class DoSomeProcessing
{
public:
process(T &t);
};
class ProcessingFrontEnd : public DoSomeProcessing<CustomerOrder>, public DoSomeProcessing<ProductionOrder>
{
};
问题是,当我使用 CustomerOrder 作为参数调用 ProcessingFrontEnd::process 时,编译器会抱怨它。
我试图在一个较小的测试应用程序中重现该问题。这是代码:
#include <vector>
class X : public std::vector<char>
, public std::vector<void *>
{
};
int main(void)
{
X x;
x.push_back('c');
return 0;
}
事实上,如果这是编译的,微软的 VS2010 编译器会给出这个错误:
test.cpp
test.cpp(11) : error C2385: ambiguous access of 'push_back'
could be the 'push_back' in base 'std::vector<char,std::allocator<char> >'
or could be the 'push_back' in base 'std::vector<void *,std::allocator<void *> >'
test.cpp(11) : error C3861: 'push_back': identifier not found
我在调用中使用不同类型(char+void*、double+void*)和不同参数('c'、3.14)测试了这个测试应用程序,但错误消息始终相同。
I tested this with VS2005 and VS2010 but I always get the same error.
Why can't the compiler determine the correct function to call? What makes this confusing for the compiler? Or is it just a bug in the Microsoft compiler?
EDIT: If I explicitly add 2 push_back methods to my class, like this:
class X : public std::vector<char>
, public std::vector<void *>
{
public:
void push_back(char c) {}
void push_back(void *p) {}
};
The compiler doesn't complain anymore. So with these methods he can clearly distinguish between a character and a void-pointer. Why can't he do this if the two push_back methods are inherited from the parent?