使用模板专业化重载返回类型?
class Base
{
public:
string Test() { return "hi"; }
};
class Derived : public Base
{
public:
int Test() { return 3; }
}
我想要基地的一声“嗨”。如何让 string s = Derived().Test()
工作?不,Test
没有参数。
我尝试使用 Base::Derived,但似乎仅返回类型不同的重载函数不会被继承/公开。我无法从客户端代码引用 Base
,因为 Base
将由模板生成。客户知道他想要的类型。我也无法让 Test
通过继承来工作。
class Base
{
public:
string Test() { return "hi"; }
};
class Derived : public Base
{
public:
int Test() { return 3; }
}
I want "hi" from Base. How is it possible to get string s = Derived().Test()
to work? And no, Test
has no parameters.
I tried using Base::Derived
, but it seems that overloaded functions that only differ in return types are not inherited/exposed. I cannot reference Base
from the client code, since Base
will be template generated. The client knows the type it wants. I couldn't get Test<string>()
to work through inheritance either.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
那是因为你不是超载,而是隐藏。
您需要转换回基类。
不能根据返回类型重载函数:
1.3.11 签名
That's because you're not overloading, but hiding.
You need to cast back to the base class.
You can't overload functions based on return type:
1.3.11 signature
如果您使用 C++11 ,您可以执行以下操作:
检查: http://ideone.com/blXhN
If you're on C++11 , you can do :
check: http://ideone.com/blXhN
像这样:
string s = Derived().Base::Test();
您的编译器不会通过基本类型进行搜索,但如果您告诉它去哪里,它会找到正确的函数看。
Like this:
string s = Derived().Base::Test();
Your compiler won't go on a quest through base types, but it will find the right function if you tell it where to look.