在模板类之外定义函数,同时使用类型和非类型参数

Define Function Outside of template class with both type and non-type parameters

本文关键字:类型 类型参数 函数 定义      更新时间:2023-10-16
template <typename T, int a, UINT32 B>
class Test
{
    public:
        Test(T, int);
        void foo();
        int bar();
};

如何定义此类之外的构造函数和函数?

只需在构造函数/方法定义之前包含完整的模板"规范",并且在限定方法/构造函数名称时,还将模板参数名称包含在类名后的尖括号中。

喜欢这个:

#include <iostream> 
#include <vector>
template <typename T, int a, int b>
class Test
{
    public:
        Test(T t, int i);
        void foo();
        int bar();
};
template <typename T, int a, int b>
Test<T, a, b>::Test(T t, int i)
{
    std::cout << "Constructor, i = " << i << std::endl;
}
template <typename T, int a, int b>
void Test<T, a, b>::foo()
{
    std::cout << "foo() Template params:" << a << " " << b << std::endl;
}
template <typename T, int a, int b>
int Test<T, a, b>::bar()
{
    std::cout << "bar() Template params:" << a << " " << b << std::endl;
}
int main()
{
    Test<std::vector<double>, 13, 42> t(std::vector<double>(2), 5);
    t.foo();
    t.bar();
}
template <typename T, int a, int B>
Test<T, a, B>::Test(T x1, int x2)
{
}

对于函数也可以以相同的方式完成。