提问人:user1899020 提问时间:12/8/2014 更新时间:12/8/2014 访问量:87
如何将类的静态方法引入命名空间?
How to introduce a static method of a class to a namespace?
问:
例如,我有一个类和一个类的静态方法。我有一个命名空间,想将 A::foo 引入命名空间。我尝试以下方法A
foo
nm
namespace nm {
using A::foo;
void f()
{
foo(...); // use A::foo
}
}
但是无法编译,因为 A 不是命名空间,因此 using 指令在这里不起作用。有什么方法可以实现这个想法吗?我想在我的 GUI 项目中将其用于 QObject::tr 和 QObject::connect 以节省一些空间。
答:
3赞
Columbo
12/8/2014
#1
不是直接的。[命名空间.udecl]/8:
集体成员的使用声明应为成员声明。[ 示例:
struct X { int i; static int s; } void f() { using X::i; // error: X::i is a class member // and this is not a member declaration. using X::s; // error: X::s is a class member // and this is not a member declaration. }
— 结束示例 ]
但是您可以模拟使用 SFINAE 和完美转发:foo
template <typename... Args>
auto foo(Args&&... args)
-> decltype(A::foo(std::forward<Args>(args)...))
{
return A::foo(std::forward<Args>(args)...);
}
评论
0赞
Deduplicator
12/8/2014
嗯。也许我们应该为类成员引入该名称的所有符号。using static
static
0赞
Columbo
12/8/2014
@Deduplicator 这永远不会被委员会接受。
评论