具有静态函数的模板类
template class with static function
本文关键字:静态函数 更新时间:2023-10-16
我想创建一个带有静态函数的模板类
template <typename T>
class Memory
{
public:
template < typename T>
static <T>* alloc( int dim )
{
T *tmp = new T [ dim ];
return tmp;
};
}
但我总会得到
int *a = Memory::alloc<int>(5)
我不知道该怎么碰巧..
»template<class T> class Memory« used without template parameters
expected primary-expression before »int«
Fehler: expected »,« or »;« before »int«
您正在模板化类和函数,而您可能只想模板化其中之一。
这是你的意思吗?
template <typename T>
class Memory
{
public:
static T* alloc( int dim )
{
T *tmp = new T [ dim ];
return tmp;
};
}
int *a = Memory<int>::alloc(5);
这是两者的正确版本:
template <typename T>
class Memory
{
public:
template <typename U>
static U* alloc( int dim )
{
U *tmp = new U [ dim ];
return tmp;
};
}
int *a = Memory<float>::alloc<int>(5);
如果只想对函数进行模板化,则可以删除外部模板。
相关文章:
- 给定一个C++嵌套的私有结构类型,是否有从文件范围静态函数访问它的策略
- 检查编译时是否存在静态函数
- 名称隐藏对静态函数继承的实例使用
- 如果 C 函数仍然可以间接执行(通过回调函数),那么将它声明为静态函数是否是一种不好的做法?
- 类中静态函数C++意外结果
- 在工人类中使用不同类的静态函数进行实验
- 类 Referention 中C++回调函数引用非静态函数
- 指向模板上下文中的成员函数或静态函数的指针
- 如何检测 Clang AST C++中的静态函数
- 内联asm编译器屏障(内存阻塞器)是算作外部函数,还是算作静态函数调用
- 如何在静态函数中使用成员函数数组
- (2 问题)"类"类型重新定义(即使 #pragma 一次),以及静态函数内的静态成员对象初始化?
- 生成代码(在编译时)以调用模板的每个实例化的静态函数
- C++无法访问或使用静态函数
- 如何将 cpp 文件中的静态函数公开给其他文件
- 将函数的引用设置为其他 c++ 文件中的非静态函数
- 方法的静态函数的等价性
- 扩展包含静态函数的类
- 非静态函数可以访问静态变量吗?
- 调用非静态函数作为谓词?