如何调用模板函数的每个实例化函数
How can I call every instantiated function of a template function?
是否可以以某种方式调用模板函数的每个实例化,而不知道在编写代码时将实例化什么?
#include <iostream>
template<typename T>
void print_size_of()
{
std::cout << sizeof(T) << "n";
}
int main()
{
print_size_of<int>();
print_size_of<double>();
//won't work but maybe it shows what i want to do:
template<typename T>
print_size_of<T>();
//is there a syntax so that the compiler replaces that with `print_size_of<int>(); print_size_of<double>();`
}
这是可能的;您需要在函数模板主体中添加一些静态变量来记录这些实例化。
在下面的代码中,每个实例化的函数都有一个静态变量,其构造函数会将函数指针注册到全局注册中心:
std::vector<void(*)()> funcs;
struct helper {
explicit helper(void (*f)()) { funcs.push_back(f); }
};
template<typename T>
void print_size_of()
{
static helper _(&print_size_of<T>);
std::cout << sizeof(T) << "n";
}
int main()
{
print_size_of<int>();
print_size_of<double>();
std::cout << "All instantiation:n";
for ( auto f : funcs ) {
f();
}
}
编辑:
这不是严格记录实例化。它只记录之前被调用的人。如果您通过其他方法(例如获取其地址(实例化它:
void (*f)() = &print_size_of<short>;
但是不要调用它,那么这个函数指针就不会被注册。
编辑2:
事实上,可以忠实地记录所有实例化。关键点是将函数模板的实例化与类模板的实例化相关联。然后,将保证该类的静态成员在进入函数之前初始化main()
。
// this one is to make sure `funcs` is initialized
auto &get_funcs() {
static std::vector<void(*)()> funcs;
return funcs;
}
template<void (*f)()>
struct helper {
helper() { get_funcs().push_back(f); }
// this is a static class member, whose initialization is before main()
static helper _ins;
};
template<void (*f)()> helper<f> helper<f>::_ins;
template<typename T>
void print_size_of()
{
// force instantiation of a class
const void *_ = &helper<&print_size_of<T>>::_ins;
std::cout << sizeof(T) << "n";
}
int main()
{
print_size_of<int>();
print_size_of<double>();
void (*f)() = &print_size_of<short>;
std::cout << "All instantiation:n";
for ( auto f : get_funcs() ) {
f();
}
}
不,这是不可能的。
您可以通过调用已经调用过一次的每个实例来接近(使用静态变量在第一次调用时注册(,但这是您能做的最好的事情。
相关文章:
- 如何使用非默认构造函数实例化模板化类
- C++ - 使用另一个类的构造函数实例化一个对象
- 与参数匹配的友元模板函数实例化
- 在保证复制的世界中构造函数实例化
- SFINAE 和模板函数实例化:为什么在启用了 SFINAE 类型的函数参数中使用模板参数时无法推断模板参数?
- 防止复制构造函数实例化 C++11 类"deleting"
- 如何键入定义一个专门的 std::set 模板,使用特定的比较函数实例化
- 使用不同类型的模板函数实例化
- C 调用模板构造函数实例化
- 为什么很清楚模板函数实例化不会内联
- 模板函数实例化文件
- 模板函数实例化的可移植性问题
- 模板函数实例化 自定义数据类型的问题
- 模板类成员函数实例化
- C++.对象使用错误的构造函数实例化
- C++如何用参数化构造函数实例化对象
- 为什么无法使用复制构造函数实例化"non const"而可以在没有复制构造函数的情况下实例化配对?
- 双模板化函数实例化失败
- 延迟 crtp 基类中的成员函数实例化
- 如何根据容器的元素类型启用模板函数实例化