c++ - 使用模板特化重载返回类型?

标签 c++ overloading template-specialization

class Base
{
public:
    string Test() { return "hi"; }
};

class Derived : public Base
{
public:
    int Test() { return 3; }
}

我想要 Base 的“嗨”。怎么可能得到string s = Derived().Test()上类?不,Test没有参数。

我试过了 using Base::Derived ,但似乎仅返回类型不同的重载函数未被继承/公开。我无法引用 Base来自客户端代码,因为 Base将生成模板。客户知道它想要的类型。我无法获得 Test<string>()也可以通过继承来工作。

最佳答案

那是因为你不是在重载,而是在隐藏。

你需要转换回基类。

Derived d;
d.Test();  //calls Derived::Test()
static_cast<Base>(d).Test(); //calls Base::Text()

不能根据返回类型重载函数:

1.3.11签名

the information about a function that participates in overload resolution (13.3): its parameter-type-list (8.3.5) and, if the function is a class member, the cv-qualifiers (if any) on the function itself and the class in which the member function is declared. [...]

关于c++ - 使用模板特化重载返回类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9368404/

相关文章:

c++ - 根据类模板的类型参数自动化类模板的大小参数

c++ - 当对象作为基本类型传递时如何创建派生对象拷贝? C++

c++ - 如何在 Cmake/Kdevelop 中使用/包含库

c++ - 错误说, "statement cannot resolve address of overloaded function"

javascript - 函数定义的下一个参数取决于第一个参数

c++ - 如何将 enable_if 用于模板类成员的外联定义

c++ - 在 C 中嵌入 XUL 后端

c++ - 如何使用boyer_moore_search在内存中搜索char *字符串?

java - 具有不同泛型的方法参数是否使方法具有不同的签名?

c++ - 使用概念的模板类方法特化