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

98 Views Asked by At

For example, I have a class A and a static method foo for the class. I have a namespace nm and want to introduce A::foo to the namespace. I try the following

namespace nm {
    using A::foo;

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

But cannot compile because A is not a namespace, thus using directive does not work here. Any way to implement this idea? I want to use it for QObject::tr and QObject::connect in my GUI project to save some space.

1

There are 1 best solutions below

2
On BEST ANSWER

Not directly. [namespace.udecl]/8:

A using-declaration for a class member shall be a member-declaration. [ Example:

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.
}

— end example ]

But you can simulate foo using SFINAE and perfect forwarding:

template <typename... Args>
auto foo(Args&&... args)
  -> decltype(A::foo(std::forward<Args>(args)...))
{
    return    A::foo(std::forward<Args>(args)...);
}