using 声明是否可以仅引用基于 const 限定的特定重载?

New*_*ine 6 c++

如果基类同时具有 const 和非 const 版本的函数,我可以通过 using 关键字在派生类中仅引用其中之一吗?

struct Base
{
protected:
    int x = 1;

    const int&  getX() const     {return x;}
    int&        getX()           {return x;}
};

struct Derived : public Base
{
public:
    using Base::getX; // Can we refer to the const or the non-const only?
};
Run Code Online (Sandbox Code Playgroud)

const getX()如果不是,在 Derived 中公开而不重复函数体的最简单方法是什么?

Nic*_*las 3

using总是带有给定名称的整个重载集。您不能调用using特定函数,只能调用其名称,其中包括该名称的所有使用。

您必须使用您喜欢的签名编写函数的派生类版本,以调用基类。最简单的方法是使用decltype(auto) getX() const { return Base::getX(); }.