【问题标题】:C++ template: multidimensional array as inputC++ 模板:多维数组作为输入
【发布时间】:2018-06-26 21:08:42
【问题描述】:

我正在尝试为 C++ 项目实现 API 层,这是我想要实现的一个小示例:

double data[8] = {0,1,2,3,4,5,6,7};

template<typename T>
void cpy(T *buf){
    for(int i=0; i<8; i++)
        buf[i] = (T)data[i];
}

int main() {
    int a[8];
    cpy(a);

    float b[8];
    cpy(b);

    double c[2][4]; 
    cpy(c); //error: functional cast to array type 'double [4]'

    return 0;
}

这个想法是允许用户将函数 cpy() 用于不同类型的数组,而不必执行 cpy&lt;double&gt;(c)cpy((double *)c) 但在此示例中,使用 2D 数组调用 cpy() 会导致编译错误:

error: expected initializer before 'cpy'
 In instantiation of 'void cpy(T*) [with T = double [4]]':
  required from here
error: functional cast to array type 'double [4]'

我们怎样才能做到这一点?

【问题讨论】:

  • 您可以使用 std::arraystd::vector,结合 std::transform 进行强制转换,这是用于将连续数据数组存储在堆栈 (std::array) 或堆 ( std::vector) 内存,它已经实现了必要的复制功能,并且不需要您的样板代码。
  • cpy(&amp;c[0][0]); ? cpy(c); 将是 cpy&lt;double(*)[4]&gt;(c);
  • @Xirema,是的,你是对的。使用 std::array 和 std::vector 更有意义。但是使用原生 C 数组可以做到这一点吗?
  • @Jarod42,要求是完全cpy(c)那样实现API,而无需指定任何数据类型(或知道数组维度/大小)。
  • @hhy 这是家庭作业吗?如果不是,那么您应该尝试更改 API,因为这种设计对于专业项目来说非常糟糕。如果是为了作业,那你真的别无选择。

标签: c++ arrays templates multidimensional-array


【解决方案1】:

假设您无法更改main()(除了缺少; 的错字)。 您可以添加重载:

template<typename T>
void cpy(T *buf){
    for (int i = 0; i != 8; ++i) {
        buf[i] = data[i];
    }
}

template<typename T, std::size_t N>
void cpy(T (*buf)[N]){
    cpy(&buf[0][0]);
}

Demo

【讨论】:

  • 正是我要找的!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-14
  • 1970-01-01
  • 2019-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-29
相关资源
最近更新 更多