C未引用类的静态变量

在以下程序中打印“Here”:
#include <iostream>
class Base
{
  static bool temp;
  static bool initTemp()
  {std::cout<<"Here\n";return true;}
};

bool Base::temp = Base::initTemp();

class Derived : public Base
{};

int main() {int a;std::cin>>a;}

在以下程序中,“此处”未打印:

#include <iostream>
template <class T>
class Base
{
  static bool temp;
  static bool initTemp()
  {std::cout<<"Here\n";return true;}
};

template <class T>
bool Base<T>::temp = Base<T>::initTemp();

class Derived : public Base<int>
{};

int main() {int a;std::cin>>a;}

在这两种情况下,Base都不会被引用.唯一的区别是在第二种情况下它是一个模板类.谁能向我解释为什么会出现这种情况.我正在使用VS 2012.

解决方法

In both cases Base is never referenced.

这正是您没有看到任何打印到标准输出的原因.

除非使用该数据成员,否则不会实例化类模板的静态数据成员的定义;与成员函数一样,类模板的静态数据成员的定义也是按需实例化的.

这在C 11标准第14.7.1 / 1段中有详细说明:

[…] The implicit instantiation of a class template specialization causes the implicit
instantiation of the declarations,but not of the deFinitions or default arguments,of the class member functions,
member classes,scoped member enumerations,static data members and member templates. […]

由于您的客户端代码从不引用Base<> :: temp,因此无需构造和初始化它.

作为附注,这个签名:

void main()

无效(标准)C.如果要编写可移植代码,main()的返回类型应始终为int.

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...