C ++中的模板类中的静态字段初始化 [英] Static field initialization in template class in C++

查看:120
本文介绍了C ++中的模板类中的静态字段初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在C ++中创建一些自我注册类。因此,我尝试了类似此处提供的解决方案。

I'm trying to create some self-registering classes in C++. So I tried the solution similar to the one provided here. While doing this I stumble over something strange.

以下是代码:

#include <iostream>

class StaticClassType {
public:
  StaticClassType() {
    // Notify when the static member is created
    std::cout << "We're in." << std::endl;
  }
};


template<typename T>
class TestClass1 {
public:
  TestClass1() { &m; }
private:
  // Static member in a template class
  static StaticClassType m;
};

template<typename T>
StaticClassType TestClass1<T>::m;


class TestClass2 : public TestClass1<TestClass2> {
public:
  TestClass2() { } // required; why?
};


int main() {
  return 0;
}

此代码创建静态成员变量 TestClass1 ::启动时(因此在控制台上打印We're in。) - 即在 main()之前启动。但是,如果我为 TestClass2 (如示例所示)编写一个(空)构造函数,代码才能工作。

This code create the static member variable TestClass1::m on startup (thereby printing "We're in." to the console) - i.e. before main() is started. However, the code only works if I write a (empty) constructor for TestClass2 (as shown in the example).

为什么我需要编写这个构造函数?为什么编译器生成的默认构造函数不会做同样的事情?

Why do I need to write this constructor? Why doesn't the default constructor generated by the compiler does the same thing?

这个问题只出现在模板类中。如果 TestClass1 不是模板类,代码将无需为 TestClass2 编写空构造函数即可工作。

This problem only occurs for template classes. If TestClass1 wasn't a template class, the code would work without writing the empty constructor for TestClass2.

推荐答案

我创建了更小的示例(没有构造函数,不需要):

I created even smaller example (without constructors, which are not needed) :

#include <iostream>

class StaticClassType {
public:
  StaticClassType(int v) {
    // Notify when the static member is created
    std::cout << "We're in."<<v << std::endl;
  }
};


template<typename T>
class TestClass1 {
protected:
  // Static member in a template class
  static StaticClassType m;
};

template<typename T>
StaticClassType TestClass1<T>::m = StaticClassType(3);


class TestClass2 : public TestClass1<TestClass2> {
public:
    void foo()
    {
        (void)m;
    }
};

int main() {
  std::cout << "main" << std::endl;
}

注意需要foo()方法,否则编译器会删除静态变量,因为它不会在任何地方使用。

take a note that foo() method is needed, otherwise the compiler removes the static variable, since it's not used anywhere.

这篇关于C ++中的模板类中的静态字段初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆