C++

edited March 2007 in Software
I'm making a template class called Container with only one problem.

part of the assignments requirement is that I have to have a function that will print the contents of the class.

The other part is that it must work with a structure.

I am unsure as to how I should get the print function to show the contents of a structure...

Comments

  • are you printing any arbitrary class/structure or do you know beforehand what's inside?
  • I know whats inside:
    eg

    struct Location{
    string street;
    string country;
    };

    Location place;
    place.street = "4th";
    place.country = "Canada";
  • as long as they're publically accessible just access them like a normal struct/class member:
    printf(place.street);
    printf(place.country);
    /* of course, the standard streams (i.e. cout) will work */
    
  • I think you missed this part
    "I have to have a function that will print the contents of the class. "

    like so:
    template <class TYPE>
    void Container<TYPE>::PrintContainer(void)
    {
    	cout << "Content: \n";
    	for(int i = 0; i < _Index; i++)
    	{
    		cout << setw(15) << "arry[" << i << "]: " << setw(15) << arry[i] << endl;
    	}
    
    }
    

    This method works for any non-object variable type (numbers, chars, strings) but not for a struct.

    I don't know of anyway to test a variable to see wether it is an object/struct other than trying to access one of its attributes, which will cause compile errors when used with non-objects.
  • there's no automatic way to access a struct, you need to work on each individual element:
    cout << setw(15) << "place.street: " place.street << endl;
    
    c++ has no way of knowing what's in a struct. structs are, at their simplest, just a way for the compiler to calculate proper pointer offsets, it doesn't keep track of what's inside, just the size of the elements.
  • Hm, I guess it would help if I understood pointers more.

    I'm no stranger to OOP, and I understand C++ cannot automatically know whats in a struct.

    Is there a way to determine if a variable is a struct?

    like for an array you can do:

    sizeof array / sizeof array[0];

    and for a struct you can do:

    sizeof location / sizeof location.here;

    but this wont compile because of the template TYPE not always being a struct.
  • Hmm, that's an interesting one...unfortunately, I do C more than C++, so I have little experience in templates. :| You might want to try asking someplace like here.
Sign In or Register to comment.