英文:
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 <typename T>
class DerivedLow : public T
{
void method()
{
ident = 0; // Refers to the global entity.
}
};
using Derived = DerivedLow<Base>;
Then nothing from the base class will be accessible in the derived class by default. You can still access base members with this->
or Base::
, or by importing them with using
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论