使用模板专业化重载返回类型?

发布于 2025-01-07 06:18:56 字数 420 浏览 2 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

时光礼记 2025-01-14 06:18:56

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

您需要转换回基类。

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

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

1.3.11 签名

参与重载的函数的信息
分辨率(13.3):其参数类型列表(8.3.5),并且,如果
函数是类成员,函数上的 cv 限定符(如果有)
本身和声明成员函数的类。 [...]

That's because you're not overloading, but hiding.

You need to cast back to the base class.

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

You can't overload functions based on return type:

1.3.11 signature

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. [...]

天荒地未老 2025-01-14 06:18:56

如果您使用 C++11 ,您可以执行以下操作:

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

class Derived : public Base
{
public:
    template<typename T= decltype(Test())>
    T Test() { return Base::Test(); }
};

检查: http://ideone.com/blXhN

If you're on C++11 , you can do :

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

class Derived : public Base
{
public:
    template<typename T= decltype(Test())>
    T Test() { return Base::Test(); }
};

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文