显式实例化模板的静态成员和另一个静态变量的初始化顺序

Order of initialization of static member of explicitly instantiated template and another static variable

这是我的问题的简化形式(基于真实的库):

// class template with static member variable:
template <typename T>
struct X 
{
  static std::vector<T> v_;
};

// definition of that static member variable:
template <typename T>
std::vector<T> X<T>::v_{};

// explicit instantiation of the class template:
template struct X<int>;

// library initialization function that fills v_ for X<int>:
static bool init()
{
  X<int>::v_.reserve(1000);
  ...
  return true;
}

// automatic initialization:
static bool initialized = init();

我的问题是,在这种情况下(单个翻译单元)是否可以保证——按照定义和实例化的顺序——X<int>::v_ 将在调用 init() 函数之前被初始化。


A​​FAIK,静态变量按照其定义的顺序在单个翻译单元中初始化,但是模板和显式实例化可以改变它吗?如果删除该显式实例化怎么办?或者,放在源码末尾?

[basic.start.dynamic]:

Dynamic initialization of a non-local variable with static storage duration is unordered if the variable is an implicitly or explicitly instantiated specialization, is partially-ordered if the variable is an inline variable that is not an implicitly or explicitly instantiated specialization, and otherwise is ordered.

[Note 1: An explicitly specialized non-inline static data member or variable template specialization has ordered initialization. — end note]

正如标准指出的那样,v_ 的初始化是 无序的

但是我们总是可以通过static函数来解决这个问题:

template<typename T>
struct X{
    static std::vector<T>& v_() noexcept {
        static std::vector<T> v;
        return v;
    }
};
template struct X<int>;
static bool init(){
    X<int>::v_().reserve(1000);
    // ...
    return true;
}
static bool initialized = init();