首页 > 解决方案 > 具有数组或向量参数的类模板

问题描述

我需要编写一个带有两个模板参数(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) {...};
   }

但我无法让构造函数的第一个参数匹配所有三种类型。

任何建议表示赞赏,谢谢!

标签: c++arraystemplatesvectorclass-template

解决方案


据我了解,问题是第一个参数是模板中的数组。尝试以下构造函数:

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、...


推荐阅读