我正在考虑使用 CRTP 类来帮助重载,并想知道以下代码会做什么:
#include <iostream>
#include <typeinfo>
template <class TDerived>
class FunctionImplementation
{
};
class AbstractFunction
{
};
class BaseFunction : public AbstractFunction, public FunctionImplementation<BaseFunction>
{
};
class DerivedFunction : public BaseFunction, public FunctionImplementation<DerivedFunction>
{
};
template <class TDerived>
void foo(const FunctionImplementation<TDerived>& function) {
std::cout << "In foo for " << typeid(TDerived).name() << std::endl;
}
int main() {
BaseFunction base;
DerivedFunction derived;
foo(base);
foo(derived);
}
在 OS X 上使用 GCC 4.2 时,它无法编译:
overload.cpp: In function ‘int main()’:
overload.cpp:31: error: no matching function for call to ‘foo(DerivedFunction&)’
在同一系统上使用 Clang 4.0,它在运行时编译并执行“自然”的事情:
In foo for 12BaseFunction
In foo for 15DerivedFunction
使用 Visual C++ 2010,它也可以编译但运行方式不同:
In foo for class BaseFunction
In foo for class BaseFunction
最后,Linux 上的 GCC 4.7.2 不会编译,但会给出更完整且相当权威的错误消息:
overload.cpp: In function ‘int main()’:
overload.cpp:31:16: error: no matching function for call to ‘foo(DerivedFunction&)’
overload.cpp:31:16: note: candidate is:
overload.cpp:22:6: note: template<class TDerived> void foo(const FunctionImplementation<TDerived>&)
overload.cpp:22:6: note: template argument deduction/substitution failed:
overload.cpp:31:16: note: ‘DerivedFunction’ is an ambiguous base class of ‘const FunctionImplementation<TDerived>’
哪个是对的?我不是导航语言标准的专家...