【发布时间】:2023-01-09 11:24:24
【问题描述】:
在函数内部,可以使用 using 声明在当前作用域中导入名称,例如
namespace A {
int y;
}
void f() { using A::y; }
using 声明可以在类定义中使用,以改变继承成员的可访问性,但显式引入从模板类继承的成员也很有用
template <bool activate>
struct A {
int x;
};
template <bool activate>
struct B : public A<activate> {
using A<activate>::x;
};
这特别有用,因为它避免了通过this->x或A<activate>::x访问x的需要。这只能在定义主体内部使用,而不能在成员函数内部使用。
template <bool activate>
struct A {
int x;
};
template <bool activate>
struct B : public A<activate> {
int f() const noexcept {
// This gives: "error: using-declaration for member at non-class scope"
// using A<activate>::x;
return x;
}
};
这种语言限制是否有理由,也就是说,using A<activate>::x 只能放在类的定义中?
【问题讨论】:
-
fyi MSVC 编译这个 - 现场 - godbolt.org/z/4d6Txb5M8
-
顺便说一句,如果激活是
false,using A<true>::x将不起作用 -
@RichardCritten 直到你实例化
f。 -
@AspectOfTheNoob 啊,对不起,我当然打算
using A<activate>::x,我修改了问题 -
同时,你可以
auto& x = A<activate>::x;。 Demo
标签: c++ language-lawyer using-directives