如何创建一个返回任何结构数组的函数

时间:2014-02-22 18:45:11

标签: c++ arrays templates struct return

我知道必须有一种更好更简单的方法来做我想做的事情所以我很抱歉我缺乏编程知识。当我调用函数printStructValue时,我的程序崩溃了。我留下了评论来解释我的思考过程。

#include <iostream>
#include <vector>
using namespace std;

struct selection   //vector array to tell me what is selected. ex:'w',5 is wall 5 
{    
  char c;
  int id;
}; vector<selection> Sel(20,selection());

struct walls       //struct to hold wall data
{
  int id;
  int x,y,z;
  int spriteState;
}; walls W[10];

struct floors     //struct to hold floor data
{
  int id;
  int x,y,z;
}; floors F[10];


template <typename T,typename U> 
T returnAnyArray(int st, T t,U u)  //function that returns any type passed
{
  if(st==1){t;}  //if st==1, then return the first, walls W
  if(st==2){u;}  //if st==2, then return the second, floors F
}

template <typename T> 
void printStructValue(T t, int d)  //print any struct value 
{ 
  cout<<"passed:"<<t[d].x<<endl; 
}

int main()
{  
  W[7].x=204;   //init value
  F[7].x= 73;   //init value

  //what I would like to happen is...  
  printStructValue( (returnAnyArray(1,W,F)),7);  //W is returned and passed so W[7].x gets printed.
  printStructValue( (returnAnyArray(2,W,F)),7);  //F is returned and passed so F[7].x gets printed.

  system("pause");
}

4 个答案:

答案 0 :(得分:1)

您的returnAnyArray函数必须返回一些内容,但类型也必须匹配。试试这个

template<typename T, typename U> 
auto returnAnyArray(int st, T t, U u) -> decltype(st == 1 ? t : u)
{
    return st == 1 ? t : u;
}

答案 1 :(得分:0)

你的模板函数returnAnyArray实际上并没有返回任何内容。因此,printStructValue正在传递垃圾指针。我很惊讶编译器没有发现这一点并打印出警告或错误。也许是因为它是一个模板。

答案 2 :(得分:0)

有些工作,但可能不是你所期待的?

#include <iostream>
#include <vector>
using namespace std;

struct walls     //struct to hold wall data
{
  int id;
  int x,y,z;
  int spriteState;
}; 
walls W[10];

struct floors //struct to hold floor data
{
  int id;
  int x,y,z;
}; 
floors F[10];

void printStructValue(walls * t, int d)  //print any struct value 
{ 
  cout<<"passed:" << t[d].x<<endl; 
}

void printStructValue(floors * t, int d)  //print any struct value 
{ 
  cout<<"passed:"<< t[d].x<<endl; 
}

int main()
{  
  W[7].x=204;   //init value
  F[7].x= 73;   //init value

  //what I would like to happen is...  
  printStructValue( W,7);  //W is returned and passed so W[7].x gets printed.
  printStructValue( F,7);  //F is returned and passed so F[7].x gets printed.

}

答案 3 :(得分:0)

以C ++的方式做到:

struct structuralMember {
  virtual ~structualMember() { }
  virtual void printme(std::ostream& out) = 0;
};

struct walls : public structualMember {      
  int x;
  void printme(std::ostream& out) { out << x; }
  };

struct floors : public structuralMember {
  int x;
  void printme(std::ostream& out) { out << x; }
  };

当然,这也不是非常复杂,但这是一个开始。