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

标签 c++ templates metaprogramming

我用 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/

相关文章:

c++ - 在VScode中进行调试时,如何在Docker容器中找到源代码文件夹

C++ 删除字符串上的标点符号,erase()/iterator 问题

c++ - 模板程序中的“模板前预期的主要表达式/';'”错误

c++ - 使用 typeid 警告未使用的变量

c++ - 如何创建抽象类直到派生实例化

F#如何将代码引用编译为程序集

c++ - 将 GetLastError() 变成异常

c++ - 如何定义指向类成员函数的指针

c++ - 使用 C++ 模板函数递归编译时间

ruby-on-rails - 动态定义关注的类和实例方法