使用声明不能引用 class 成员

using declaration cannot refer to class member

基本上,在命名空间 np:

中定义了一个 class Foo
//Foo.h
namespace np {

    class Foo {
        public:
          static void static_member();
         ...
        }
...
}

我想引用其他来源中的静态成员,比如 src.cc

//src.cc
#include "Foo.h"

using np::Foo::static_member;
...
static_member()
...

启动编译器后,它抱怨:

 error: using declaration cannot refer to class member

但是,当我将行更改为 np::Foo::static_member() 时它起作用了。那么,省略无穷无尽的范围前缀的正确方法是什么?

So, what are proper ways to omit the interminable scope prefixes?

没有办法。在 class 范围之外,using 声明可以引用 classes 中的嵌套 类型 ,但不能引用数据成员,请参阅 here .

你能得到的最短的是

using namespace np;
Foo::static_member();

或者使用指向成员的指针,它更短但也更容易混淆:

auto static_member = &np::Foo::static_member;
static_member();

您不必添加 using np::Foo::static_member;

如果包含 Foo.h 并且函数是 public

,则可以使用任何 static 函数

例如:

// Foo.h
namespace np
{
  Class Foo
  {
    public:
      static void PrintHello();
  }
}

// Foo.cpp
#include "Foo.h"
#include <iostream>

void np::Foo::PrintHello()
{
  printf("Hello World!\n");
}

// main.cpp
#include "Foo.h"
int Main()
{
  np::Foo::PrintHello();
}

我不确定你的用例是什么,但我会选择两种方式之一(或者三种?):

1) 如果它适用,请尝试将此静态方法移动到命名空间中 - 因为它是静态的,这可能对您有用(在您需要将此东西作为某种模板化 class 传递的情况下,然后这种方法行不通)。 看看其他人对此的看法:

Namespace + functions versus static methods on a class https://softwareengineering.stackexchange.com/questions/134540/are-utility-classes-with-nothing-but-static-members-an-anti-pattern-in-c

namespace np
{
  void static_non_member();
} // namespace np

// .. in .cpp, should be fine to do this
{
  using namespace np;
  static_non_member();
}

2) 使用声明与 classes 一起工作得很好,所以你至少可以减少你必须做的写作量:

// assume same hpp
// cpp
#include "Foo.h"

using Foo = np::Foo;

Foo::static_member();

3) 奖金回合:存储指向该函数的指针

#include <type_traits>

using FunctionPtrT = std::add_pointer<void()>::type;
FunctionPtrT static_ptr = &Foo::static_member;

// Foo::static_member();
static_ptr(); // name this whatever you wish