下面是重新创建我遇到的问题的代码。Base
class 是一个带有虚函数的模板类foo
。foo
具有添加传入参数的默认实现。
SimpleDerived
源自Base
,专门用于std::string
。SimpleDerived
重载虚Base<T>::foo()
函数。此类foo
在调用时可以正常编译,并且其输出符合预期main
。
#include <iostream>
template<class T>
struct Base
{
virtual void foo(T val)
{
T local = val + val; // THE OFFENDING LINE OF CODE
std::cout << "Base" << std::endl;
}
};
struct SimpleDerived : public Base<std::string>
{
virtual void foo(std::string val)
{
std::cout << "SimpleDerived" << std::endl;
}
};
struct SimpleObject
{
int value;
};
struct ComplexDerived : public Base<SimpleObject>
{
virtual void foo(SimpleObject val)
{
std::cout << "ComplexDerived" << std::endl;
}
};
int main(void)
{
Base<int> base;
base.foo(2);
SimpleDerived simpleDerived;
simpleDerived.foo("hello world");
SimpleObject object;
ComplexDerived complexDerived;
complexDerived.foo(object);
return 0;
}
ComplexDerived
派生自Base
,使用自定义结构对其进行专门化SimpleObject
。ComplexDerived
过载foo
也是如此。然而,这是问题的根源。如果我尝试编译它,我会得到:
quicktest.cpp: In member function ‘void Base<T>::foo(T) [with T = SimpleObject]’:
quicktest.cpp:47:1: instantiated from here
quicktest.cpp:8:19: error: no match for ‘operator+’ in ‘val + val’
显然,没有运算符“+” SimpleObject
。但这是我的困惑..编译器被要求实现Base<SimpleObject>::foo
,因为这是ComplexDerived
继承的。但是,我从不使用或调用Base<SimpleObject>::foo
. 那么编译器是否应该尝试生成这个基类函数?