在模板类之外定义函数,同时使用类型和非类型参数
Define Function Outside of template class with both type and non-type parameters
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)
{
}
对于函数也可以以相同的方式完成。
相关文章:
- 如何使用非类型模板参数传入指向数组的指针
- 通过依赖类型使用非类型模板参数的单类型模板参数类模板的部分专用化
- 在 C++ 中将非指定类型作为参数传递的最佳方法?
- 如何定义采用最通用数量和最类型的参数的函数
- 将类型声明为类型模板参数的模板参数的一部分是否合法?
- 是否可以在C++中有一个"generic"模板参数,该参数可以是非类型模板参数或类型?
- 推断指针非类型模板参数的类型
- 将空*参数转换为各种类型的参数是UB吗?
- 未命名的非类型模板参数有什么意义?
- 标准对此指向成员函数类型模板参数有何说明?是我的代码有误,还是 MSVS 16.6 有问题?
- Lambda可以用作非类型模板参数吗
- 类型为 "int*" 的参数与 C++ 中错误类型"int**"参数不兼容
- 基于类型作为参数的字符串表示形式具有不同返回类型的函数
- 具有"templated"返回类型和参数的函数指针
- 如何制作可以接受任何类型的参数的 std::函数和 lambda
- 指向(数据)成员的指针作为非类型模板参数,例如具有自动存储持续时间/无链接
- 为什么在传递长整型时调用具有两个双精度类型的参数的重载函数?
- C++ 类型的参数与 void (__cdecl*)(void) 类型的参数不兼容,当调用 std::atexit()
- 以特征类型作为参数的泛型函数回调
- 非类型模板参数