哪个接口将字符串、数组和其他类型复制到相同类型的实例

What interface will copy cstrings, arrays, and other types to instances of the same type?

本文关键字:复制 类型 同类型 实例 其他 接口 字符串 数组      更新时间:2023-10-16

不是所有类型的实例都可以复制到带有=符号的相同类型的另一个实例。

例如,

虽然它可以在int :

上工作
int x = 0;
int y = 5;
x = y; //x is now: 5

字符数组:

char x[32]="data to overwrite";
char y[32]="new data";
x = y; //incorrect

其他数组:

int x[5] = {1,2,3,4,5};
int y[5] = {6,7,8,9,10};
x = y; //incorrect

char*s:

char* x="data to overwrite";
char* y="new data";
x = y; //incorrect

如何编写一个允许我执行以下操作的重载函数?

int x = 0;
int y = 5;
Copy(x,y); //x is now: 5
char x[32]="data to overwrite";
char y[32]="new data";
Copy(x,y); //x is now: "new data"
int x[5] = {1,2,3,4,5};
int y[5] = {6,7,8,9,10};
Copy(x,y); //x is now: {6,7,8,9,10}
char* x="data to overwrite";
char* y="new data";
Copy(x,y); //x is now: "new data"

*我将假设任何抽象数据类型在其重载赋值操作符(或从编译器提供的浅拷贝)中完成必要的工作


你为什么要这样做?
为了更容易地测试遗留C代码库的某些部分,我想围绕一些组件生成一些c++包装器。由于C代码的奇怪设计,有很多我想摆脱的间接。因此,使用简单的Copy函数将变量复制到另一个实例中要容易得多,而不是解析出类型,然后决定如何将适当的复制到另一个实例变量中。

下面是一个完整的示例,其中添加了cout s以显示选择了正确的重载。

#include <algorithm>
#include <cstddef>
#include <iostream>
#include <ostream>
// default
template<class T>
void Assign(T& dst, const T& src)
{
  dst = src;
  std::cout << "assign (default)" << std::endl;
}
// arrays
template<class T1, std::size_t n>
void Assign(T1 (&dst)[n], const T1 (&src)[n])
{
  std::copy(src, src+n, dst);
  std::cout << "assign (array)" << std::endl;
}
// pointers
template<class T1>
void Assign(T1 *&dst, T1 *src)
{
  // DANGER: memory leaks/double frees
  // not exactly sure what is supposed to happen here
  // same as default for now...
  // ok as long as only string constants are passed around
  // (as is the case in the example)
  dst = src;
  std::cout << "assign (pointer)" << std::endl;
}
int main() {
  {
    int x = 0;
    int y = 5;
    Assign(x,y); //x is now: 5
  }
  {
    char x[32]="data to overwrite";
    char y[32]="new data";
    Assign(x,y); //x is now: "new data"
  }
  {
    int x[5] = {1,2,3,4,5};
    int y[5] = {6,7,8,9,10};
    Assign(x,y); //x is now: {6,7,8,9,10}
  }
  {
    const char* x="data to overwrite";
    const char* y="new data";
    Assign(x,y); //x is now: "new data"
  }
}
输出:

g++ -std=c++11 -g -Wall -O3 check.cc -o check && ./check
assign (default)
assign (array)
assign (array)
assign (pointer)

这是我对自己问题的尝试:

  #include <algorithm>
  #include <cstring>
  //catch all
  template <typename T>
  void Copy(T &x, T y)
  {
      x = y;
  }
  //overload on static array copying
  //(T[N] = T[N])
  template <typename T, size_t N>
  void Copy(T(&x)[N], T(&y)[N])
  {
      std::copy(std::begin(y), std::end(y), std::begin(x));
  }
  //overload on copying of null terminated data
  //(char array = cstring)
  void Copy(char x[], const char y[])
  {
      //assumes x is >= to y
      //not sure if I can use strncpy somewhow
      strcpy(x, y); 
  }