【问题标题】:c/c++ correct format for arrays in function templatesc/c++ 函数模板中数组的正确格式
【发布时间】:2013-10-28 13:16:11
【问题描述】:

不知道如何命名这个问题,如果这听起来有问题或具有欺骗性,请原谅我。我有一个以前从未遇到过的问题。基本上,当我必须将结构放入函数而不创建实际结构(只需要使用值)时,我会这样做:

struct a{
    int x,y,z;
};

void function(a x){ ... }

void main(void){
    function(a(34,64,75));
}

但是,现在我需要在该结构中使用一个数组,所以它看起来像..

struct a{
    int x[5];
};

void function(a x){ ... }

void main(void){
    function(a(????));
}

我不知道如何在不使用实际变量的情况下正确初始化它。只是有些不便,但我想知道答案。我试过搜索和暴力破解我的方式,但我做得不好。

感谢您的帮助

编辑:我的问题有很多复杂性,这让许多人对我的轻率感到不安。首先,我指的不是 c++ 模板,而是这个词的实际含义,抱歉我的英文不好.. 生病尝试更好地解释自己(TRY):我想做的是省略为特定函数创建结构变量的用法,并在调用该函数时自己手动定义结构成员,如您在第一个中看到的示例..但是,在第二个示例中,我真正要问的是如何在所述结构的成员位于数组中时手动定义它们。再次为我第一次发布此问题时的所有错误道歉

【问题讨论】:

  • int main()。另外,C XOR C++?没有 C/C++ 这样的东西。您的标签说 C,但模板是 C++ 功能......现在呢?
  • 使用结构体而不是实际的函数参数究竟有什么好处?
  • 在 C 中没有这样的方法。 C++ 中有,但是虽然你的标题提到了 C++,但你没有用它标记你的问题,这就是为什么我删除了我的(C++ 特定的)答案。
  • 为什么只需要一个变量的结构?谁说你没有创建结构?你只是没有保留对它的引用
  • 我更新了我的答案。但是,我不确定这是否能回答您的问题。如果你想避免 struct 和 a 只是需要使用一些数字,你可以直接为函数使用可变参数模板或简单地传递一个数字数组。

标签: c++ arrays function struct format


【解决方案1】:

我想你使用 C++。如果我正确理解您的问题,您想在不使用中间变量的情况下初始化数组。在这种情况下,您需要将适当的构造函数添加到您的结构中。

以下代码将执行此操作。但是请注意,您需要最新的编译器,例如 GCC 版本 (>= 4.6),并且应该编译为 g++ -std=c++11 file.cpp。

#include <iostream>
#include <initializer_list>
#include <algorithm> 

using namespace std;

struct s{
  int x[5];
  // constructor 1. a variant using 'initializer_list'
  s(initializer_list<int> l) { copy(l.begin(),l.end(),x); } 
  // constructor 2. using a variadic template 
  template<class ...T> s(T... l) : x{l...} {} ;             
  // constructor 3. copy from an existing array 
  s(int* l) { copy(l,l+5,x);}
};

int f(s instance){ return instance.x[2]; }

int main(){
  s a1({1,2,3,4,5});      // calls constructor 1 (or 2 if 1 is left out)
  s a2{1,2,3,4,5};        // calls constructor 1 (or 2 if 1 is left out)
  s b1(1,2,3,4,5);        // calls constructor 2
  int l[5] = {1,2,3,4,5};    
  s c1(l);                // calls constructor 3

  cout << l[2] << endl;
  cout << a.x[2] << endl;
  cout << f(s(l)) << endl;
  cout << f(s{1,2,3,4,5}) << endl;    // calls constructor 1 again (or 2 if 1 is left out)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-06
    • 2015-01-16
    • 1970-01-01
    • 2015-10-16
    • 2023-02-22
    • 1970-01-01
    • 1970-01-01
    • 2013-05-22
    相关资源
    最近更新 更多