模板静态成员变量的实例化 我试图弄明白CLAN如何确定C++模板静态成员变量需要实例化,我看到一些让我困惑的行为。

模板静态成员变量的实例化 我试图弄明白CLAN如何确定C++模板静态成员变量需要实例化,我看到一些让我困惑的行为。,c++,templates,C++,Templates,给定以下代码: #include <stdio.h> #include <typeinfo> int report(const char *name) { printf("Reporting class: %s\n", name); return 0; } template<typename ReportedClass> class reported_class { public: reported_class() {

给定以下代码:

#include <stdio.h>
#include <typeinfo>

int report(const char *name)
{
    printf("Reporting class: %s\n", name);
    return 0;
}

template<typename ReportedClass>
class reported_class
{
public:
    reported_class()
    {
        _reported_instances++;
    }

private:
    static int _reported_instances;
};

template<typename ReportedClass>
int reported_class<ReportedClass>::_reported_instances = report(typeid(ReportedClass).name());

class foo : reported_class<foo>
{
public:
    int baz() { return 0; }

};

class bar : reported_class<bar>
{
public:
    bar() { }
    int baz() { return 0; }
};

int main(int argc, char **argv)
{
    return 0;
}
为什么要实例化报告的类的静态,而不是foo的静态?唯一的区别似乎是构造函数的存在,但我希望在任何一种情况下都会调用所报告的类构造函数(因此,由于构造函数中使用了静态实例化)。在标准中是否有我不知道的原因,这是可以信赖的吗


gcc-4.7.3显示了相同的行为,因此我假设这是我误解的。

显然在未显示的
main
函数中,您没有实例化任何一个类

那么编译器就没有理由为类
foo
生成默认构造函数


没有它,就没有实例化
reported\u类的代码

添加了main()函数,正如你猜测的那样,它没有实例化任何一个类。你的解释听起来似乎有道理,但在这种情况下,所报告的类的实例化可以依赖吗,或者编译器可以在没有任何对象构造的情况下完全优化它吗?@kihlasht:我认为不会,因为标准通常都是针对类的o保留定义良好的副作用,例如,如果未使用的变量的构造函数或析构函数可能产生副作用,则不允许对其进行优化。但我不知道。因此,我建议您将此作为一个新问题来问,如果有关系的话(但就我个人而言,我宁愿确保事情按照我的意愿发生,而不是依赖于一个必须向专家询问的微妙之处,希望他们中的一位可能知道或花时间进行研究和分析,而根据墨菲定律,某些编撰者肯定会错误地处理)。
$ c++ -v
Apple LLVM version 5.0 (clang-500.0.68) (based on LLVM 3.3svn)
Target: x86_64-apple-darwin13.1.0
Thread model: posix
$ c++ test.cpp 
$ ./a.out 
Reporting class: 3bar
$