在类中取消隐藏全局标识符

huangapple go评论77阅读模式
英文:

Unshadow global identifier in a class

问题

我有以下的C++代码:
```cpp
class ident {};

class Base {
public:
  int ident;
};

class Derived : public Base {
  ::ident var; // 引用全局标识符
  ident var; // 语法错误,引用基类成员
};

是否有可能在Derived::method()中使ident引用全局标识符?最终完全隐藏Base::ident?我无法更改Base,但我可以创建一个中间类。我可以在任何地方添加代码行,但成员变量的生成始终将ident表示为ident

这是一个非常不寻常的请求,因为它是用于一个模板化的代码生成器(SWIG)。


<details>
<summary>英文:</summary>

I have the following C++ code:
```cpp
class ident {};

class Base {
public:
  int ident;
};

class Derived : public Base {
  ::ident var; // refers to the global identifier
  ident var; // syntax error, refers to the base member
};

Is it possible to make it so ident refers to the global identifier in Derived::method()? Eventually completely hiding Base::ident? I cannot change Base, but I can make an intermediate class. I can add lines everywhere but the generation of the member variables will always refer to ident as ident.

It is a very unusual request, because it is for a templated code generator (SWIG).

答案1

得分: 3

你可以添加别名来隐藏基类成员:

class Derived : public Base {
  using ident = ::ident;
  ::ident var1; // OK,与之前相同
  ident var2;   // OK,引用typename Derived::ident(因此也是::ident)
};
英文:

You might add alias to hide base member:

class Derived : public Base {
  using ident = ::ident;
  ::ident var1; // OK, as before
  ident var2;   // OK, refer to typename Derived::ident (and so ::ident)
};

答案2

得分: 0

如果您将基类依赖于模板参数:

template <typename T>
class DerivedLow : public T
{
    void method()
    {
        ident = 0; // 引用全局实体。
    }
};

using Derived = DerivedLow<Base>;

那么默认情况下,派生类中将无法访问基类的任何成员。您仍然可以使用 this->Base:: 来访问基类成员,或者通过 using 导入它们。

英文:

If you make the base depend on a template parameter:

template &lt;typename T&gt;
class DerivedLow : public T
{
    void method()
    {
        ident = 0; // Refers to the global entity.
    }
};

using Derived = DerivedLow&lt;Base&gt;;

Then nothing from the base class will be accessible in the derived class by default. You can still access base members with this-&gt; or Base::, or by importing them with using.

huangapple
  • 本文由 发表于 2023年7月17日 17:41:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/76703197.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定