以下类使用CRTP尝试将类型添加到具有Schwarz计数器的std :: vector,以确保初始化顺序。根据3.6.2 / 2,成员h_已经无序初始化。我如何更改它以确保它已订购初始化?我希望派生类除了从类中正确继承之外什么都不做。
#ifndef P_H_
#define P_H_
#include "PR.h"
template <typename T>
class P
{
class helper
{
public:
helper()
{
PR.push_back(typeid(T));
}
};
static helper h_;
};
template <typename T>
typename P<T>::helper P<T>::h_;
#endif
答案 0 :(得分:0)
此类问题的标准模式是使用生成器而不是暴露全局静态变量。 (这是C ++中的一个老问题)
所以改变:
static helper h_ ;
为:
static helper & h_() ;
并像这样定义:
template <typename T>
typename P<T>::helper & P<T>::h_()
{
static P<T>::helper value_ ;
return value_ ;
}
因此,保证在使用之前进行初始化。