收集有关在程序中实例化哪些模板变体的信息

Collecting information on which template variants are being instantiated in a program

本文关键字:信息 实例化 程序      更新时间:2023-10-16

今天我了解到,当我们有一个带有静态成员变量的C++类模板时,除非我们"以需要定义静态数据成员存在的方式使用它",否则不会调用其构造函数(实际上甚至不会定义成员)。

这种现象在这里得到了很好的解释: C++ 静态成员初始化(内部模板乐趣)

在实践中,这意味着如果我们希望进行初始化(以及它的任何可能的副作用),我们必须显式引用该静态成员的每个实例化(从类模板外部)。

我一直在思考如何克服这个问题。

我的动机是有一个现有的代码库,它使用类模板Foo的各种实例化(它有多个模板参数,但为了示例,我简化了它),我想自动收集有关所有不同参数组合的信息。

我实际上不能等待在程序执行期间构造所有这些Foo(这是一个长时间运行的后台进程),所以我认为我可以在Foo<T>中放置一个静态Initializer<T>,并让它在程序启动后立即为每个不同的Foo类型提取所需的类型信息。

在这种情况下,必须枚举Initializer<T> Foot<T>::init的所有实例化才能首先运行初始值设定项显然违背了目的。我必须去看看(在整个项目中)类型是什么,而这正是我试图自动化的。

我注意到,如果我用持有局部静态Initializer实例的静态方法替换静态成员变量,我可以更轻松地强制生成Initializer<T>定义。我只需要一个指向该方法的指针(例如,在Foo的构造函数内部)。

最后一步是在程序启动后调用此静态方法。在 g++/clang 的情况下,使用__attribute__((constructor))就像一个魅力。

不过,我还必须处理MSVC++,这就是我想出的:

#include <iostream>
#if defined(_MSC_VER) && !defined(__clang__)
#define MSVC_CONSTRUCTOR_HACK
#define ATTRIBUTE_CONSTRUCTOR
#else
#define ATTRIBUTE_CONSTRUCTOR __attribute__((constructor))
#endif
static int& gInt() { // Global counter
static int i;
return i;
}
template <class T>
struct Initializer {
// If it works, this gets called for each Foo<T> declaration
Initializer() {
gInt()++;
}
};

#ifdef MSVC_CONSTRUCTOR_HACK
__pragma(section(".CRT$XCU", read))
template <class T>  // This will hold pointers to Foo<T>::getInit
static void(*g_constructors__)(void);
#endif
template <class T>
struct Foo {
ATTRIBUTE_CONSTRUCTOR // Empty in case of MSVC
static void getInit() {
static Initializer<T> init;
}
#ifdef MSVC_CONSTRUCTOR_HACK
template <> // Why is this allowed?!
__declspec(allocate(".CRT$XCU")) static void(*g_constructors__<T>)(void) = getInit;
#endif
Foo() { // This never gets called and we want that
std::cout << "Constructed Foo!" << std::endl; 
(void)&getInit; // This triggers instantiation and definition of Initializer<T>
}
};

void unused() {
Foo<char> c;
Foo<double> d;
Foo<int> i;
Foo<float> f;
}
int main() {
std::cout << gInt() << std::endl; // prints 4
return 0;
}

它依赖于将函数指针放入 .可执行文件的 CRT 部分(https://stackoverflow.com/a/2390626/6846474、https://github.com/djdeath/glib/blob/master/glib/gconstructor.h)。

但是,为了使它在这种情况下工作,我也不得不求助于这个非常奇怪的黑客:有一个全局变量模板g_constructors__它明确地专门用于(!Foo.

老实说,我真的很惊讶这行得通。我知道它是非标准的,但有人可以解释它是如何编译的吗?这只是运气还是至少就Microsoft C++而言,它以某种方式"形成良好"?

我知道我可以使用某种外部静态分析工具来做到这一点,但这非常接近我想要的,主要优点是它都已合并到正在检查的程序中。

如果我可以为每个 T 调用初始值设定项(看起来我可以),提取类型信息很容易。我可以使用提升类型索引或我需要的任何其他内容来串化模板参数。此处使用全局计数器仅用于查看是否正在创建Initializer实例。

如果您愿意将额外变量的成本添加到对象中,这似乎可以满足您的需求,尽管这一切都非常复杂,我可能会错过一个案例:

#include <iostream>
static int& gInt() { // Global counter
static int i;
return i;
}
struct Initializer {
Initializer() { ++gInt(); }
};

template <class T>
struct Foo {
Foo() { // This never gets called and we want that
std::cout << "Constructed Foo!" << std::endl; 
}
private:
static Initializer gint_incrementer;
void* p_ = &gint_incrementer; // force existence 
};
template <typename T>
Initializer Foo<T>::gint_incrementer;
void unused() {
Foo<char> c;
Foo<char> c2;
Foo<double> d;
Foo<int> i;
Foo<float> f;
}
int main() {
std::cout << gInt() << std::endl; // prints 4
}

如果我们使用schwartz 反习语的变体,则无需黑客攻击且不需要unused()函数即可实现:

global_counter.hpp

#pragma once
struct GlobalCounter {
int next();
int value() const;
int value_ = 0;
struct init {
init();
~init();
};
};
extern GlobalCounter& globalCounter;
static GlobalCounter::init globalCounterInit;

global_counter.cpp

#include "global_counter.hpp"
#include <memory>
#include <type_traits>
static int globalCounterCount;
static std::aligned_storage_t <sizeof(GlobalCounter), alignof(GlobalCounter)> globalCounterStorage;
GlobalCounter& globalCounter = reinterpret_cast<GlobalCounter&>(globalCounterStorage);
GlobalCounter::init::init() {
if(globalCounterCount++ == 0) new (&globalCounter) GlobalCounter ();
}
GlobalCounter::init::~init() {
if (--globalCounterCount == 0) globalCounter.~GlobalCounter();
}
int GlobalCounter::next() {
return value_++;
}
int GlobalCounter::value() const {
return value_;
}

foo.hpp

#pragma once
#include "global_counter.hpp"
#include <iostream>
template <class T>
struct Foo {
Foo() { // This never gets called and we want that
std::cout << "Constructed Foo!" << std::endl;
}
static int ident;
};
template<class T>
int Foo<T>::ident;
template<class T>
struct EnableFoo
{
EnableFoo()
{
if (counter++ == 0)
Foo<T>::ident = globalCounter.next();
}
static int counter;
};
template<class T> int EnableFoo<T>::counter;

static EnableFoo<char> enableFooChar;
static EnableFoo<int> enableFooInt;
static EnableFoo<double> enableFooDouble;
static EnableFoo<float> enableFooFloat;

主.cpp

#include <iostream>
#include "foo.hpp"
int main() {
std::cout << globalCounter.value() << std::endl; // prints 4
return 0;
}

参见施瓦茨计数器:

https://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Nifty_Counter

好的,因为我问题中的解决方案只是部分的,我将分享一个工作代码片段,它实际上显示了我所追求的东西,现在我想通了。

我们不需要任何特定于编译器的黑客,以下内容应该普遍有效:

#include <iostream>
#include <vector>
#include <string>
#include <mutex>
#include <boost/type_index.hpp>
static std::vector<std::string>& getInstantiations() {
static std::vector<std::string> instantiations;
return instantiations;
}
static std::mutex& getMutex() {
static std::mutex mut;
return mut;
}
template <class T>
struct Introspection {
Introspection() { 
std::lock_guard<std::mutex> lock(getMutex());
getInstantiations().push_back(boost::typeindex::type_id<T>().pretty_name());
}
void forceExistence() {}
};

template <class... Ts>
struct Foo {
Foo() { // This never gets called and we want that
std::cout << "Constructed Foo!" << std::endl;
introspection.forceExistence();
}
private:
static Introspection<Foo<Ts...>> introspection;
};
template <class... Ts>
Introspection<Foo<Ts...>> Foo<Ts...>::introspection;
void unused() {
Foo<char> c;
Foo<char> c2;
Foo<double> d;
Foo<int, const int> i;
Foo<float, bool, long> f;
}
int main() {
for (auto& i : getInstantiations()) {
std::cout << i << std::endl;
}
/*
output:
Foo<char>
Foo<double>
Foo<int, int const>
Foo<float, bool, long>
*/
}

它看起来很愚蠢,但考虑一个更大的项目,到处都是Foo<...>声明。是的,也许我可以只使用正则表达式搜索,但这样我实际上可以在检查程序运行时使用收集的信息。回显类型名称只是我们可以用它做什么的最简单示例。