如何将类的静态方法引入命名空间

How to introduce a static method of a class to a namespace?

本文关键字:命名空间 静态方法      更新时间:2023-10-16

例如,我有一个类A和一个静态方法foo。我有一个命名空间nm,想将 A::foo 引入命名空间。我尝试以下

namespace nm {
    using A::foo;
    void f()
    {
        foo(...); // use A::foo
    }
}

但是无法编译,因为 A 不是命名空间,因此使用指令在这里不起作用。有什么方法可以实现这个想法吗?我想在我的GUI项目中将其用于QObject::tr和QObject::connect以节省一些空间。

不是直接的。[namespace.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)...);
}