作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
以下类使用 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
最佳答案
此类问题的标准模式是使用生成器而不是公开全局静态变量。 (这是C++的老问题)
所以改变:
static helper h_ ;
到:
static helper & h_() ;
然后这样定义它:
template <typename T>
typename P<T>::helper & P<T>::h_()
{
static P<T>::helper value_ ;
return value_ ;
}
这样可以保证在使用前进行初始化。
关于c++ - 使无序初始化 statc 有序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18197644/
以下类使用 CRTP 尝试将类型添加到具有 Schwarz 计数器以确保初始化顺序的 std::vector。根据 3.6.2/2 成员 h_ 具有无序初始化。我将如何更改它以确保它已订购初始化?我希
我是一名优秀的程序员,十分优秀!