gpt4 book ai didi

c++ - 使用类型和非类型参数在模板类外部定义函数

转载 作者:行者123 更新时间:2023-11-30 03:01:07 26 4
gpt4 key购买 nike

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();
}

关于c++ - 使用类型和非类型参数在模板类外部定义函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11462820/

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