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

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

Unshadow global identifier in a class

问题

  1. 我有以下的C++代码:
  2. ```cpp
  3. class ident {};
  4. class Base {
  5. public:
  6. int ident;
  7. };
  8. class Derived : public Base {
  9. ::ident var; // 引用全局标识符
  10. ident var; // 语法错误,引用基类成员
  11. };

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

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

  1. <details>
  2. <summary>英文:</summary>
  3. I have the following C++ code:
  4. ```cpp
  5. class ident {};
  6. class Base {
  7. public:
  8. int ident;
  9. };
  10. class Derived : public Base {
  11. ::ident var; // refers to the global identifier
  12. ident var; // syntax error, refers to the base member
  13. };

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

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

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

You might add alias to hide base member:

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

答案2

得分: 0

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

  1. template <typename T>
  2. class DerivedLow : public T
  3. {
  4. void method()
  5. {
  6. ident = 0; // 引用全局实体。
  7. }
  8. };
  9. using Derived = DerivedLow<Base>;

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

英文:

If you make the base depend on a template parameter:

  1. template &lt;typename T&gt;
  2. class DerivedLow : public T
  3. {
  4. void method()
  5. {
  6. ident = 0; // Refers to the global entity.
  7. }
  8. };
  9. 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:

确定