小编All*_*sch的帖子

如果静态成员函数有返回值,为什么只能在全局范围内调用它们?

我发现了一个奇怪的事情:类/结构的静态成员函数不能称为全局范围,除非它们有返回值。

这个程序不编译:

struct test
{
  static void dostuff()
  {
      std::cout << "dostuff was called." << std::endl;
  }
};

test::dostuff();

int main()
{  
   return 0;
}
Run Code Online (Sandbox Code Playgroud)

在 GCC v4.8.3 下为我们提供以下内容:

main.cpp:12:16: error: expected constructor, destructor, or type conversion before ';' token
test::dostuff();
               ^
Run Code Online (Sandbox Code Playgroud)

但是,通过向dostuff()全局变量添加返回值并将其分配给全局变量,程序将按预期编译和工作:

struct test
{
  static int dostuff()
  {
      std::cout << "dostuff was called." << std::endl;
      return 0;
  }
};

int i = test::dostuff();

int main()
{
   return 0;
}
Run Code Online (Sandbox Code Playgroud)

这产生了预期的输出:

dostuff was called.
Run Code Online (Sandbox Code Playgroud)

谁能向我解释为什么会这样,以及是否有不涉及创建全局变量的解决方法?

c++ static member-functions

5
推荐指数
1
解决办法
114
查看次数

实现CRTP链表混合C++

我无法让CRTP mixin工作.

这是剥离的实现:

template < typename T >
class AutoSList : public T {
public:
  AutoSList() {}

  ~AutoSList() : _next(nullptr) {}


private:
  static T* _head;
  static T* _tail;
  T* _next;

};

// I really hate this syntax.
template <typename T>
T*  AutoSList<T>::_head = nullptr;
template <typename T>
T*  AutoSList<T>::_tail = nullptr;

class itsybase : public AutoSList < itsybase >
{

};
Run Code Online (Sandbox Code Playgroud)

我正在使用VS2013并收到以下错误:

   error C2504: 'itsybase' : base class undefined
 : see reference to class template instantiation 'AutoSList<itsybase>' being compiled
Run Code Online (Sandbox Code Playgroud)

我不知道出了什么问题,有什么建议吗?

c++ templates mixins crtp

0
推荐指数
1
解决办法
252
查看次数

标签 统计

c++ ×2

crtp ×1

member-functions ×1

mixins ×1

static ×1

templates ×1