gpt4 book ai didi

c++ - 模板函数的实例化

转载 作者:搜寻专家 更新时间:2023-10-31 02:02:40 25 4
gpt4 key购买 nike

我用 C++ 模板做了一些实验,这就是我得到的:

标题.hpp

template <typename T0>
class A
{
void foo0(T0 t0);

template <typename T1>
void foo1 (T0 t0, T1 t1);
};

源代码.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++ - 模板函数的实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56921059/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com