如何将类的静态方法引入命名空间
How to introduce a static method of a class to a namespace?
例如,我有一个类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)...);
}
相关文章:
- 如何通过命名空间调用非静态方法
- 转发声明在命名空间中不起作用的替代方法
- 使用 GMock 的具有命名空间的模拟方法
- 在方法定义中显式指定命名空间
- 使用类指针重载C++命名空间函数模板专用化替代方法?
- 匿名命名空间中的const与静态const
- C++详细介绍命名空间 vs 匿名 vs 私有方法到类 vs. pimpl vs. 朋友类
- 使用匿名命名空间中的函数或另一个文件中的静态函数不应该出错吗?
- 是否有一个很好的方法可以在C 11中打印出像JSON一样的Trie结构(仅迭代解决方案)的扁平命名空间
- 从类方法调用命名空间中名为 Same 的函数时,重载解析失败
- 将typeID转换为静态成员访问(C )的命名空间
- 为什么主可执行文件和 dlopen 加载的共享库共享命名空间静态变量的一个副本?
- 为在与类方法中的类相同的命名空间中定义的结构调用重载运算符
- 获取封装在命名空间中的静态变量地址
- 有没有一种方法可以创建具有广义属性的命名空间
- 用于命名模板静态类方法的特定实例的语法
- 如何将类的静态方法引入命名空间
- 来自命名空间的方法链接
- 命名空间“静态”是否仍在 C++11 中弃用
- 使用命名空间和静态方法时出现问题