模板函数的实例化
Instantiation of a template function
我用 C++ 模板做了一些实验,这就是我得到的:
header.hpp
template <typename T0>
class A
{
void foo0(T0 t0);
template <typename T1>
void foo1 (T0 t0, T1 t1);
};
source.cpp
// foo0 body
// ...
// foo1 body
// ...
// And instantiations of class A and foo0 for types "float" and "double"
template class A<float>;
template class A<double>;
// for foo1 uses separately instantiations
// instantiation foo1 for type "int"
template void A<float>::foo1<int>(float t0, int t1);
template void A<double>::foo1<int>(double t0, int t1);
正如我们所见,foo1 的实例化需要重新枚举 T0 类型。 C++ 中是否有一种实例化 foo1 的方法,它使用先前创建的 类 实例的枚举?喜欢
template void A<T0>::foo1<int>(float t0, int t1);
我认为使用类型别名是实现此目的的一种 C++ 方法。你可以有这样的东西:
template <typename T0>
class A
{
void foo0(T0 t0);
using myType = T0;
template <typename T1>
void foo1(T0 t0, T1 t1);
};
template void A<float>::foo1<int>(A::myType t0, int t1);
template void A<double>::foo1<int>(A::myType t0, int t1);
这就是您如何统一模板函数实例化的第一个参数。
我用 C++ 模板做了一些实验,这就是我得到的:
header.hpp
template <typename T0>
class A
{
void foo0(T0 t0);
template <typename T1>
void foo1 (T0 t0, T1 t1);
};
source.cpp
// foo0 body
// ...
// foo1 body
// ...
// And instantiations of class A and foo0 for types "float" and "double"
template class A<float>;
template class A<double>;
// for foo1 uses separately instantiations
// instantiation foo1 for type "int"
template void A<float>::foo1<int>(float t0, int t1);
template void A<double>::foo1<int>(double t0, int t1);
正如我们所见,foo1 的实例化需要重新枚举 T0 类型。 C++ 中是否有一种实例化 foo1 的方法,它使用先前创建的 类 实例的枚举?喜欢
template void A<T0>::foo1<int>(float t0, int t1);
我认为使用类型别名是实现此目的的一种 C++ 方法。你可以有这样的东西:
template <typename T0>
class A
{
void foo0(T0 t0);
using myType = T0;
template <typename T1>
void foo1(T0 t0, T1 t1);
};
template void A<float>::foo1<int>(A::myType t0, int t1);
template void A<double>::foo1<int>(A::myType t0, int t1);
这就是您如何统一模板函数实例化的第一个参数。