当我使用 g++ 5.4.0 时,下面的示例代码按预期工作,但在我将 g++ 更新为 10.2.0 后,结果发生了变化。我也在clang++ 11.0.1上测试了示例代码,结果和g++ 5.4.0一样。
我搜索了一些相关的问题,但没有得到有效的答案。据我所知,重载函数应该在模板之前匹配,为什么g++ 10.2.0得到不同的结果,我该如何解决?
因为原始源代码非常复杂,所以用其他c++特性重构它们并不容易,这个问题可以通过较小的改动来解决吗?
示例代码的目标是使用重载函数Base::operator const std::string&()执行一些特殊动作,使用模板函数执行常见动作。
#include <string>
#include <iostream>
class Base
{
public:
template <class T>
operator const T&() const;
virtual operator const std::string&() const;
};
template <class T>
Base::operator const T&() const
{
std::cout << "use template method" << std::endl;
static T tmp{};
return tmp;
}
Base::operator const std::string&() const
{
std::cout << "use overload method" << std::endl;
const static std::string tmp;
return tmp;
}
template …Run Code Online (Sandbox Code Playgroud)