gpt4 book ai didi

c++ - "using"关键字是否可以继承较少的功能?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:22:02 25 4
gpt4 key购买 nike

Derived 中有一个 template foo(T)Base 中有 2 个 foo() 重载。

struct Base
{
void foo (int x) {}
void foo (double x) {}
};

struct Derived : Base
{
template<typename T> void foo (T x) {}
using Base::foo;
};

现在,当 foo()Derived 对象调用时;如果适用,我只想使用 Base::foo(int),否则它应该调用 Derived::foo(T)

Derived obj;
obj.foo(4); // calls B::foo(int)
obj.foo(4.5); // calls B::foo(double) <-- can we call Derived::foo(T) ?

简而言之,我想要的效果是:

using Base::foo(int);

这可能吗?以上只是一个例子。

最佳答案

using 将所有重载带入作用域。只需将它隐藏在派生类中,它的编写要多一些但可以完成工作:

struct Derived : Base
{
template<typename T> void foo (T x) {}
void foo(int x){
Base::foo(x);
}
};

关于c++ - "using"关键字是否可以继承较少的功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6149798/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com