如何调用模板函数的每个实例化函数?

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:

事实上,忠实记录所有实例化是可以的。关键点是将函数模板的实例化关联到class模板的实例化。然后 class 的静态成员将保证在进入 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();
    }
}

不,那不可能。

您可以通过调用已经调用过一次的每个实例化来关闭(使用静态变量在第一次调用时注册),但这是您能做的最好的事情。