c++ - 具有数组或向量参数的类模板
问题描述
我需要编写一个带有两个模板参数(type、functor)和两个模板参数(array/std::vector、int)的类模板定义,它们可以执行以下代码:
const char* message= "Message";
const transform<char, firstFunctor> first(message, lengthOfMessage);
transform_view<int, secondFunctor> second(intArray, intSize);
transform<double, thirdFunctor> third(doubleArray, doubleSize);
数组/向量的类型必须与第一个模板参数的类型相匹配。
我尝试了一些这样的变体:
template <typename A, typename B>
class transform
{
public:
transform<A, B>(A[], B) {...};
}
但我无法让构造函数的第一个参数匹配所有三种类型。
任何建议表示赞赏,谢谢!
解决方案
据我了解,问题是第一个参数是模板中的数组。尝试以下构造函数:
transform(A* arr, B el){
//now here is a tricky part, because there is a very big difference
//between a char*, and an int/double/unsigned/float/... *.
}
如果您在类中有一个 A 类型的数组,并且想要将其更改为传递的数组:
private:
A* my_array;
你可以这样尝试:
if(dynamic_cast<char*>(arr)) //if arr is of type char* {
if (this->my_array != nullptr) delete my_array; //not needed if in a basic constructor...
size_t len = strlen(arr);
my_array = new char [len + 1];
strcpy(this->my_array, arr); //(destination, source)
my_array[len] = '\0';
}
else //if it is a numeric array
{
this->my_array = arr;
//redirecting the pointers in enough
}
哦,如果你在 Visual Studio 上,如果你写 strcpy 将工作
文件顶部的“#pragma 警告(禁用:4996)”。
否则,它会将其标记为不安全并建议 strncpy、strcpy_s、...
推荐阅读
- memory-management - 如何测量 Julia 中一小部分代码的内存使用情况?
- ios - 如何在自定义键盘扩展中检查连接的外部键盘?
- python - Django - 基于多对多关联限制选择
- azure-ad-b2c - 在联合 Azure AD B2C 注册自定义策略流上获取 UPN 的问题
- java - 为什么需要获取未检查的番石榴期货
- netlify - 如何在 netlify 上部署站点?
- angular - 读写JSON结构
- node.js - 在 IIS 上运行的 Node.js 应用程序在浏览器中无法访问物理文件
- c# - 自定义工具栏,菜单图标不显示 Xamarin Android
- python - 如何在 pdb 模式下直接进入我的个人 python 函数忽略站点包 lib 代码?