5

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

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

我在 .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;
}

如果我想在 .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);

如果我开始有很多类型的 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>;

但它不起作用。

4

0 回答 0