这个问题是关于如何在运行之前使用全局变量初始化来实现一些副作用main()
(例如,工厂类注册之前main()
)。当涉及模板时,这可能会很棘手。考虑以下代码:
template <class T>
class A {
public:
static bool flag;
static bool do_something() {
// Side effect: do something here.
}
template <bool&>
struct Dummy {};
// Important: Do not delete.
// This line forces the instantiation and initialization of `flag`.
using DummyType = Dummy<flag>;
};
template <class T>
bool A<T>::flag = A<T>::do_something();
// A<int>::flag is instantiated and.
// A<int>::do_something will be called before main to initialize A<int>::flag.
class B : A<int> {};
如果我们删除using
,行为会有所不同:
template <class T>
class A {
public:
static bool flag;
static bool do_something() {
// Side effect: do something here.
}
// The `using` dummy part is missing.
};
template <class T>
bool A<T>::flag = A<T>::do_something();
// A<int>::flag is not instantiated.
// A<int>::do_something will not be called.
class B : A<int> {};
我的问题:using
这里的技巧是编译器特定的东西,还是由 C++ 标准支持?我做了一些搜索,发现了一些关于标准 14.7.1 的相关信息,但仍然不确定规则,using
因为它在 14.7.1 中没有提到(我的来源是这个,不确定它是否应该被视为基本事实)。此外,这using Dummy
对我来说似乎有点 hacky。是否有任何其他解决方法可以使其更优雅?目标是解决class A
自身内部的实例化,以便与副作用相关的代码段保持私有。