类模板的成员函数模板的显式实例化

Tel*_*oze 7 c++ templates explicit-instantiation

假设我的头文件中有一个带有成员函数模板的类模板。

//file.hxx
template<class T>
struct A {
    T val;
    template<class U> foo(U a);
};
Run Code Online (Sandbox Code Playgroud)

我在 .cpp 中有 foo 的实现:

//file.cpp
#include "file.hxx"
#include <typeinfo>
template<class T> template<class U>
A<T>::foo<U>(U a){
    std::cout << "Type T: " << typeid(val).name() << std::endl;
    std::cout << "Type U: " << typeid(a).name() << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

如果我想在 .cpp 文件中显式实例化我的类和成员函数(例如 int 和 float),我需要类似以下内容:

template struct A<int>;
template struct A<float>;
template A<int>::foo<int>(int);
template A<int>::foo<float>(float);
template A<float>::foo<int>(int);
template A<float>::foo<float>(float);
Run Code Online (Sandbox Code Playgroud)

如果我开始有很多类型的 T 和 U,这会变得有点冗长。有没有更快的方法可以做到这一点,并且仍然在 cpp 文件中显式实例化模板?我在想象类似的事情

template<class T>
template A<T>::foo<int>(int);
template<class T>
template A<T>::foo<float>(float);
template struct A<int>;
template struct A<float>;
Run Code Online (Sandbox Code Playgroud)

但它不起作用。